浮点比较给出了不同的结果 [英] Float comparison gives different results
问题描述
#include h取代;
int main(){
float a = 0.9;
if(a <0.9)
printf(hi); //这将是答案
else
printf(bye);
返回0;
$ p如果我们将0.9更改为0.8,则会打印其他语句: p>
#include< stdio.h>
int main(){
float a = 0.8;
if(a <0.8)
printf(hi);
else
printf(bye); //这将是答案
return 0;
$ b 那么为什么当我们改变一个数字时这个输出会改变呢?
解决方案您必须知道浮点是如何工作的。
浮点通过使用2的幂数,每个数字用来表示 2 ^ -x
,其中X是第n位数字。
例如, 0.011
(二进制)将是 2 ^ -2 + 2 ^ -3
,这是 0.25 + 0.125 = 0.375
现在尝试表示 0.9
。你有麻烦了,因为没有二的力量来代表它。在32位和可能的64位机器中表示的值将给出略小于0.9的结果,而对于0.8而言,结果是精确的,并且可以由2的幂来表示。
b
$ b 你可以通过打开 python
提示来试试。尝试输入一些数字,最后以 ... 99999999
结尾。
Look at the following two codes, and tell me the reason why answers vary a lot.
#include<stdio.h>
int main() {
float a = 0.9;
if(a<0.9)
printf("hi"); // This will be the answer
else
printf("bye");
return 0;
}
And if we change 0.9 to 0.8, then else's statement is printed:
#include<stdio.h>
int main() {
float a = 0.8;
if(a<0.8)
printf("hi");
else
printf("bye");//this will be the answer
return 0;
}
So why this output changes when we just change a single digit?
解决方案 You have to know how floating points works.
Floating points are represented by using powers of two, each digit is used to represent 2^-x
where X is the n-th digit.
For example, 0.011
(binary) would be 2^-2 + 2^-3
, which is 0.25 + 0.125 = 0.375
Now try to represent 0.9
. You are in trouble, since no power of two to represent it. The value this is represented in 32-bits and probably 64-bits machines will give a result slightly smaller than 0.9, whereas for 0.8 the result is precise and representable by powers of two.
You can try this out by opening a python
prompt. Try and type a few numbers, eventually one will end with ...99999999
.
这篇关于浮点比较给出了不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!