问题描述
为什么这个节目没有给出输出float和double数据类型。然而,会是怎样的结果,当在同一code替换循环??
#包括LT&;&stdio.h中GT; 诠释的main()
{
浮动X = 1.1;
而(X = = 1.1)
{
的printf(%F \\ N,X);
X = X-0.1;
}
返回0;
}
浮动X = 1.1;
而(X = = 1.1)
float和double变量不能够存储1.1的精确值,只有极近似的。在浮动和双精确值会略有不同,由于在precision的区别。
1.1是一个的双的值。您存储1.1作为双成浮动,这将轻微改变的值。然后你用双值1.1进行比较,所以它不会很相等,因此绝不会进入你的病情。
对于这个工作,你需要写1.1F,以确保您使用相同的数据类型无处不在的工作。
此外,我敢肯定,别人会解释为什么严格相等比较浮点值往往是一个坏主意。
Why does this program gives no output for float and double datatypes. However, what will be the result when the same code is replaced with for loop??
# include <stdio.h>
int main()
{
float x=1.1;
while (x==1.1)
{
printf("%f\n",x);
x=x-0.1;
}
return 0;
}
float x=1.1;
while (x==1.1)
float and double variables are not capable of storing the exact value of 1.1, only a very close approximation. The exact value in a float and a double will be slightly different due to the difference in precision.
1.1 is a double value. You are storing 1.1 as a double into a float which will slightly alter the value. Then you compare it with the double value 1.1 so it will not quite be equal and so will never enter your condition.
For this to work you need to write 1.1f to ensure that you are working with the same data type everywhere.In addition I'm sure someone else will explain why comparing floating point values for exact equality is often a bad idea.
这篇关于为什么这个节目没有给出输出float和double数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!