相关疑难解决方法(0)

如何检查浮动的依赖关系

我想确定(在c ++中)一个浮点数是否是另一个浮点数的乘法逆.问题是我必须使用第三个变量来完成它.例如这段代码:

float x=5,y=0.2;
if(x==(1/y)) cout<<"They are the multiplicative inverse of eachother"<<endl;
else cout<<"They are NOT the multiplicative inverse of eachother"<<endl;
Run Code Online (Sandbox Code Playgroud)

将输出:"他们不是......"这是错的,这段代码:

float x=5,y=0.2,z;
z=1/y;
if(x==z) cout<<"They are the multiplicative inverse of eachother"<<endl;
else cout<<"They are NOT the multiplicative inverse of eachother"<<endl;
Run Code Online (Sandbox Code Playgroud)

将输出:"他们......"这是正确的.
为什么会这样?

c++ algorithm floating-point inverse floating-accuracy

12
推荐指数
3
解决办法
794
查看次数

Java,C,C++等中十进制数的精度

假设我们有这种循环(伪代码)

double d = 0.0
for i in 1..10 {
    d = d + 0.1
    print(d)
}
Run Code Online (Sandbox Code Playgroud)

在C与printf("%f", d)我得到这个:

0.100000
0.200000
0.300000
...
1.000000
Run Code Online (Sandbox Code Playgroud)

在C++中,cout << d我得到了这个:

0.1
0.2
...
1
Run Code Online (Sandbox Code Playgroud)

在Java中,System.out.println(d)我得到了这个:

0.1
0.2
0.3 (in debug mode, I see 0.30000000000004 there but it prints 0.3)
...
0.7
0.799999999999999
0.899999999999999
0.999999999999999
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

  1. 为什么这个简单的代码用Java打印得如此糟糕且在C中是否正确?
  2. 这在其他语言中如何表现?

c c++ java decimal decimal-point

2
推荐指数
2
解决办法
1568
查看次数