为什么双类型变量返回Nan?

Ana*_*aya 2 .net c#

我试图解决二次方程.我有double类型的所有变量,以及s变量Nan的结果.

double a, b, c, x1, d, x2, s ;
Console.WriteLine("Enter a value a: ");
a = double.Parse(Console.ReadLine());
Console.WriteLine("Enter a value b: ");
b = double.Parse(Console.ReadLine());
Console.WriteLine("Enter a value c: ");
c = double.Parse(Console.ReadLine());

d = b * b - 4 * a * c;

Console.WriteLine("solution: ");

Console.WriteLine("1) Substitute the values entered in the equation " + "{0} * x^2 + {1} * x + {2} = 0 ", a, b, c);
Console.WriteLine("2) ?alculate the discriminant: d = b * b - 4 * a * c ");
Console.WriteLine("3) D = {0}*{0} - 4*{1}*{2} = {3}", b, a, c, d);


if (d > 0)
{
    x1 = (-b + Math.Sqrt(d))/2*a;
    x2 = (-b - Math.Sqrt(d))/2*a;
    s = (a * Math.Sqrt(x2) )+ (b * x1) + c;
    Console.WriteLine("{0} ; {1}",x1,x2);
    Console.WriteLine("?heck: " + "{0} * {1} + {2} * {3} + {4} = {5} ", a, x2, b, x1, c, s);

}
else if (d == 0)
{
    x1 = (-b)/2*a;
    Console.WriteLine(x1);
}
else if (d < 0)
{
    Console.WriteLine("Since the discriminant is less than zero, then the equation has no solution.");
}
Run Code Online (Sandbox Code Playgroud)

以下字符串返回Nan s =(a*Math.Sqrt(x2))+(b*x1)+ c; 为什么是南而不是双?

Jon*_*eet 6

为什么是南而不是双

NaN不是一种类型,它是一种价值 - 我怀疑你是因为它x2是负面的.负数的平方根的结果在实数中是未定义的(与复数相反),因此Math.Sqrt对于负输入返回NaN("非数字"),如下所述:

d parameter                 Return value
Zero or positive            The positive square root of d.
Negative                    NaN
Equals NaN                  NaN
Equals PositiveInfinity     PositiveInfinity
Run Code Online (Sandbox Code Playgroud)

double.NaN 记录为:

表示不是数字(NaN)的值.该字段是常量.
...
当操作结果未定义时,方法或运算符返回NaN.