This does not answer the question.
我在 Java 和 C# 中运行完全相同的代码,但它给出了两个不同的结果。
为什么?由于两种语言的 double 具有完全相同的 specifications :
double is a type that represents 64-bit IEEE 754 floating-point number in Java
double is a type that represents 64-bit double-precision number in IEEE 754 format in C#.
Java
double a = Math.pow(Math.sin(3), 2);
double b = Math.pow(Math.cos(3), 2);
System.out.println(a); // 0.01991485667481699
System.out.println(b); // 0.9800851433251829
System.out.println(a+b); // 0.9999999999999999
C#
double a = Math.Pow(Math.Sin(3), 2);
double b = Math.Pow(Math.Cos(3), 2);
Console.WriteLine(a); // 0.019914856674817
Console.WriteLine(b); // 0.980085143325183
Console.WriteLine(a+b); // 1
最佳答案
这只是 C# 与 writeLine
方法一起使用的精度。参见 https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString其中指定 G 格式说明符提供 15 位精度。
如果你写:
Console.WriteLine(a.ToString("R"));
它打印 0.019914856674816989
。
关于java - Java 和 C# 之间 double 精度的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33743481/