谁能解释为什么这段代码输出“真实”? [英] can anyone please explain why this code is outputting "true"?
问题描述
#include < stdio.h >
int main(){
float a = 0 。 7 ;
if (a< 0。 7 ){
printf( true);
}
else {
printf( 假跨度>);
}
return 0 ;
}
你在代码中写的任何东西都必须以二进制形式存储在内存中(0,1形式)
当你写浮点数a = 0.7然后必须得到0.7的二进制值。
二进制0.7是
b0。 1011001100110011001100110011001100110011001100110011001100110 ...
但是,0.7是双精度字面值,其值为0.7舍入到最接近的可表示的双精度值,即:
b0。 10110011001100110011001100110011001100110011001100110
十进制,这正是:
0 。 6999999999999999555910790149937383830547332763671875
当写一个浮点数a = 0.7时,该双精度值再次舍入为单精度,并且a获取二进制值:
b0。 101100110011001100110011
这正是
< span class =code-digit> 0 。 699999988079071044921875
十进制。
进行比较时(a< 0.7),您将这个单精度值(转换为double,不会舍入,因为所有单精度值都可以双精度表示)与原始双精度值进行比较。
< pre lang =c#> 0 。 699999988079071044921875 < 0 。 6999999999999999555910790149937383830547332763671875
比较正确返回true。
请访问此链接进行浮点运算airth>
浮点Airthmatic [ ^ ]
你好,
在C编程语言中,浮点常数默认是双重类型,这就是0.7 i的原因s double类型,除非使用'f'或'F'后缀来表示浮点类型。因此浮点变量a小于双常数0.7。
#include< stdio。 h取代;
int main()
{
浮动a = 0.7;
printf(%。10f%.10f \ n,0.7,a);
返回0;
}
< /stdio.h>
O / P将是
0.7000000000 0.6999999881
因此满足if条件并打印true
#include<stdio.h>
int main(){
float a=0.7;
if(a<0.7){
printf("true");
}
else{
printf("false");
}
return 0;
}
Any thing you write in code must be stored in memory in binary form (0,1 form)
When you write float a=0.7 then a must get the binary value of 0.7.
In binary 0.7 is
b0.1011001100110011001100110011001100110011001100110011001100110...
However, 0.7 is a double-precision literal, whose value is 0.7 rounded to the closest representable double-precision value, which is:
b0.10110011001100110011001100110011001100110011001100110
In decimal, that's exactly:
0.6999999999999999555910790149937383830547332763671875
When you write float a = 0.7, that double value is rounded again to single-precision, and a gets the binary value:
b0.101100110011001100110011
which is exactly
0.699999988079071044921875
in decimal.
When you do the comparison (a < 0.7), you are comparing this single-precision value (converted to double, which does not round, because all single-precision values are representable in double precision) to the original double-precision value.
0.699999988079071044921875 < 0.6999999999999999555910790149937383830547332763671875
the comparison correctly returns true.
Please visit this link for Floating point airthmatic operation
Floating Point Airthmatic[^]
Hello ,
In C programming language, the floating point constant is double type by default, that's why 0.7 is double type, unless use 'f' or 'F' suffix to indicate float type.Hence the float variable a is less than double constant 0.7.
#include<stdio.h> int main() { float a=0.7; printf("%.10f %.10f\n",0.7, a); return 0; } </stdio.h>
O/P will be
0.7000000000 0.6999999881
Hence the if condition is satisfied and it prints "true"
这篇关于谁能解释为什么这段代码输出“真实”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!