为什么 C# 返回“?”?
Why does C# returning "?"?
所以我刚开始尝试使用 C#。我有一行代码,输出是一个“?”。
代码:Console.WriteLine(Math.Pow(Math.Exp(1200), 0.005d));
输出:?
我正在使用 Visual Studio,它还显示 exited with code 0
。
它应该输出403.4287934927351
。我也用 Geogebra 试过了,它是正确的,如图所示,所以它不是无穷大。
C# double
类型(由 Math.Exp
函数 return 编辑)是固定大小的类型(64 位),因此它不能表示任意大数。它可以表示的最大数字是 double.MaxValue
常数,它的阶数为 10^308,小于您要计算的数 (e^2000)。
当计算结果超过最大可表示值时 - 表示无穷大的特殊“数字”被 returned。所以
double x = Math.Exp(1200); // cannot represent this with double type
bool isInifinite = double.IsInfinity(x); // true
在你得到这个“无穷大”之后 - 所有其他涉及它的计算将只是 return 无穷大,他们无能为力。那么整个表达式 Math.Pow(Math.Exp(1200), 0.005d))
returns "infinity".
当您尝试将结果写入控制台时,它会转换为字符串。 rules将提到的无穷大转换为字符串如下:
Regardless of the format string, if the value of a Single or Double
floating-point type is positive infinity, negative infinity, or not a
number (NaN), the formatted string is the value of the respective
PositiveInfinitySymbol, NegativeInfinitySymbol, or NaNSymbol property
that is specified by the currently applicable NumberFormatInfo object.
在您当前的文化中,PositiveInfinitySymbol
可能是“∞”,但您的控制台编码可能无法表示此符号,因此输出“?”。您可以像这样将控制台编码更改为 UTF8:
Console.OutputEncoding = Encoding.UTF8;
然后就会正确显示"∞"
据我所知,没有框架提供的类型可以处理任意大小的有理数。对于整数,虽然有 BigInteger
类型。
在这种特定情况下,您可以只使用 double
,因为您可以使用以下方法做同样的事情:
Console.WriteLine(Math.Exp(1200 * 0.005d));
// outputs 403.4287934927351
现在没有超过 double
容量的中间结果,因此工作正常。
对于不可能的情况 - 有第三方库允许使用任意大的有理数。
所以我刚开始尝试使用 C#。我有一行代码,输出是一个“?”。
代码:Console.WriteLine(Math.Pow(Math.Exp(1200), 0.005d));
输出:?
我正在使用 Visual Studio,它还显示 exited with code 0
。
它应该输出403.4287934927351
。我也用 Geogebra 试过了,它是正确的,如图所示,所以它不是无穷大。
C# double
类型(由 Math.Exp
函数 return 编辑)是固定大小的类型(64 位),因此它不能表示任意大数。它可以表示的最大数字是 double.MaxValue
常数,它的阶数为 10^308,小于您要计算的数 (e^2000)。
当计算结果超过最大可表示值时 - 表示无穷大的特殊“数字”被 returned。所以
double x = Math.Exp(1200); // cannot represent this with double type
bool isInifinite = double.IsInfinity(x); // true
在你得到这个“无穷大”之后 - 所有其他涉及它的计算将只是 return 无穷大,他们无能为力。那么整个表达式 Math.Pow(Math.Exp(1200), 0.005d))
returns "infinity".
当您尝试将结果写入控制台时,它会转换为字符串。 rules将提到的无穷大转换为字符串如下:
Regardless of the format string, if the value of a Single or Double floating-point type is positive infinity, negative infinity, or not a number (NaN), the formatted string is the value of the respective PositiveInfinitySymbol, NegativeInfinitySymbol, or NaNSymbol property that is specified by the currently applicable NumberFormatInfo object.
在您当前的文化中,PositiveInfinitySymbol
可能是“∞”,但您的控制台编码可能无法表示此符号,因此输出“?”。您可以像这样将控制台编码更改为 UTF8:
Console.OutputEncoding = Encoding.UTF8;
然后就会正确显示"∞"
据我所知,没有框架提供的类型可以处理任意大小的有理数。对于整数,虽然有 BigInteger
类型。
在这种特定情况下,您可以只使用 double
,因为您可以使用以下方法做同样的事情:
Console.WriteLine(Math.Exp(1200 * 0.005d));
// outputs 403.4287934927351
现在没有超过 double
容量的中间结果,因此工作正常。
对于不可能的情况 - 有第三方库允许使用任意大的有理数。