gpt4 book ai didi

c# - 为什么 double 型变量返回 Nan?

转载 作者:行者123 更新时间:2023-11-30 20:22:35 26 4
gpt4 key购买 nike

我正在尝试求解二次方程。我有所有 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.");
}

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

最佳答案

Why it is Nan and not double

NaN 不是类型,它是 - 我怀疑您理解它是因为x2 是负数。负数的平方根的结果在实数中未定义(与复数相反),因此 Math.Sqrt 为负输入返回 NaN(“不是数字”),as documented :

d parameter                 Return value
Zero or positive The positive square root of d.
Negative NaN
Equals NaN NaN
Equals PositiveInfinity PositiveInfinity

double.NaN记录为:

Represents a value that is not a number (NaN). This field is constant.
...
A method or operator returns NaN when the result of an operation is undefined.

关于c# - 为什么 double 型变量返回 Nan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com