问题描述
我刚刚遇到网站,并试图用Java和C ++来做这件事。为什么在Java中编写以下内容会产生0.30000000000000004
I just came across this website and tried doing that in Java and C++. Why writing the following in Java gives 0.30000000000000004
double x = 0.1 + 0.2;
System.out.print(x);
用C ++编写以下内容给出0.3?
Whereas writing the following in C++ gives 0.3?
double x = 0.1 + 0.2;
cout<<x;
推荐答案
C ++标准无法保证,因此结果实际上是实现定义的。但是,大多数实现都会这样做。
There is no guarantee from the C++ standard that IEEE 754 floating point arithmetic is used, so the result is actually implementation defined. However, most implementations will do it.
在Java中, float
和 double
。此外,您可以添加一个类或方法声明的修饰符,要求严格的IEEE 754浮点运算甚至用于中间结果。
In Java, float
and double
are defined to be IEEE 754 floating point types. In addition, you can add the strictfp
modifier to a class or method declaration to require strict IEEE 754 floating point arithmetic be used even for intermediary results.
在处理浮点数时,如果有疑问,查看实际位表示通常很有用。
When dealing with floating point numbers, in case of doubt, it is often useful to look at the actual bit representation.
#include <cstdint>
#include <cstdio>
int
main()
{
static_assert(sizeof(double) == sizeof(uint64_t), "wrong bit sizes");
const double x = 0.1 + 0.2;
const uint64_t bits = *reinterpret_cast<const uint64_t *>(&x);
printf("C++: 0x%016lX\n", bits);
return 0;
}
public final class Main {
public static void main(final String[] args) {
final double x = 0.1 + 0.2;
final long bits = Double.doubleToLongBits(x);
System.out.printf("Java: 0x%016X\n", bits);
}
}
当我在计算机上执行这两个程序时(GNU / Linux与GCC和OpenJDK),输出
When I execute both programs on my computer (GNU/Linux with GCC and OpenJDK), the output is
C++: 0x3FD3333333333334
Java: 0x3FD3333333333334
表明两者都产生完全相同的结果。但是,便携式程序不应该依赖于此。
which shows that both yield the exact same result. However, a portable program should not rely on this.
这篇关于为什么在C ++和Java中使用float函数会产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!