我想确定(在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)
将输出:"他们......"这是正确的.
为什么会这样?
假设我们有这种循环(伪代码)
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)
所以我的问题是: