解决一个 bug 我有一些有趣的发现。
这个过程的结果
static void Main(string[] args)
{
int i4 = 4;
Console.WriteLine("int i4 = 4;");
Console.WriteLine("i4 % 1 = {0}", i4 % 1);
double d4 = 4.0;
Console.WriteLine("double d4 = 4.0;");
Console.WriteLine("d4 % 1 = {0}", d4 % 1);
Console.WriteLine("-----------------------------------------------------------");
int i64 = 64;
double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0);
Console.WriteLine("int i64 = 64;");
Console.WriteLine("double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = {0}", dCubeRootOf64);
Console.WriteLine("dCubeRootOf64 = {0}", dCubeRootOf64);
Console.WriteLine("dCubeRootOf64 % 1 = {0} ?????????????? Why 1. ??????????", dCubeRootOf64 % 1);
Console.ReadLine();
}
是
int i4 = 4;
i4 % 1 = 0
double d4 = 4.0;
d4 % 1 = 0
-----------------------------------------------------------
int i64 = 64;
double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = 4
dCubeRootOf64 = 4
dCubeRootOf64 % 1 = 1 ?????????????? Why 1. ??????????
int 4 % 1 = 0
-- 正确
double 4.0 % 1 = 0
-- 正确
但错误在于:
Math.Pow(64, 1.0/3.0) % 1 = 1
64 的立方根是 4。为什么在那种情况下 4 % 1 = 1
?
最佳答案
Math.Pow(64, 1.0/3.0)
返回 3.9999999999999996
。
显示时四舍五入为 4
。
将其取模 1 返回 0.99999999999999956
,显示时类似地四舍五入为 1
。
您可以通过添加 .ToString("R")
查看真实值
关于模运算符中的 C# 错误 %,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10743745/