我刚刚写了我的第一个C#程序 .
这是一段解码二次方程的简单代码 .
它完美地适用于某些功能(例如-6x2-6x 12),而对于其他功能(4x2-20x 25),它表现出我怀疑是舍入错误 .
我是C#的新手,我看不出问题;有人能帮我调试这段代码吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
int d;
double x1, x2;
entA: Console.Write("a?");
try
{
a = Convert.ToInt32(Console.ReadLine());
}
catch
{
/*If a=0, the equation isn't quadratic*/
Console.WriteLine("Invalid input");
goto entA;
}
entB: Console.Write("b?");
try
{
b = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid input");
goto entB;
}
entC: Console.Write("c?");
try
{
c = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid input");
goto entC;
}
/*Calculating a discriminant*/
d = b * b - 4 * a * c;
if (d == 0)
{
x1 = x2 = -b / (2 * a);
Console.WriteLine("The only solution is x={0}.", x1);
Console.ReadLine();
}
else if (d < 0) /*If d<0, no solutions are possible*/
{
Console.WriteLine("There are no possible solutions");
Console.ReadLine();
}
else /*If d>0, there are two possible solutions*/
{
x1 = (-b - Math.Sqrt(d)) / (2 * a);
x2 = (-b + Math.Sqrt(d)) / (2 * a);
Console.WriteLine("x1={0} and x2={1}.", x1, x2);
Console.ReadLine();
}
}
}
}
这是更新的代码:
namespace ConsoleApplication7
{
class Program
{
static int ObtainInput(string prompt, bool canBeZero)
{
double a = ObtainInput("A? ", false);
double b = ObtainInput("B? ", true);
double c = ObtainInput("C? ", true);
double d;
double x1, x2;
while (true) // loop forever!
{
Console.Write(prompt);
string input = Console.ReadLine();
int result;
bool success = int.TryParse(input, out result);
if (success && (canBeZero || result != 0))
return result;
Console.WriteLine("Invalid input!");
}
/Calculating a discriminant/
d = b * b - 4 * a * c;
if (d == 0)
{
x1 = x2 = -b / (2 * a);
Console.WriteLine("The only solution is x={0}.", x1);
Console.ReadLine();
}
else if (d < 0) /If d<0, no solutions are possible/
{
Console.WriteLine("There are no possible solutions");
Console.ReadLine();
}
else /If d>0, there are two possible solutions/
{
x1 = (-b - Math.Sqrt(d)) / (2 * a);
x2 = (-b + Math.Sqrt(d)) / (2 * a);
Console.WriteLine("x1={0} and x2={1}.", x1, x2);
Console.ReadLine();
}
}
}
}
3 回答
真棒 . 现在是不养成坏习惯的好时机:
问题比比皆是 . 首先,使用
int.TryParse
,而不是尝试捕捉可能失败的东西 .其次,注释与代码的操作不匹配 . 代码确定结果是否为整数;评论说它检查零 .
第三,当你试图表示的是一个循环时,不要使用goto .
第四,看看所有重复的代码!你有相同的代码重复三次,只有很小的变化 .
让自己成为一个帮助方法:
现在你的主线是:
你的错误在这里:
您以整数运算,然后转换为双精度 . 也就是说,你进行除法,舍入到最接近的整数,然后转换为double . 从一开始就做双打(或者,不太可能,小数) . 它应该是:
也就是说,a,b和c不应该是整数 .
分配给x1和x2时,你正在进行整数除法; (您可以将2更改为2.0以将其更改为双重除法并获得双倍结果)
将a,b,c和d值更改为双倍也可能有意义,这也将超出问题,并允许人们输入系数的非int值 .
int a,b,c; int d;
首先,尝试使用double而不是int,因为1/3 = 0使用整数 .