[英]Float to int in C unexpected output
I have the following code in C 我在C中有以下代码
#include <stdio.h>
int main()
{
float a = 1.88;
a =a - (0.25 * 7 + 0.1 * 1);
a = a *100;
printf("a = %f\n",a );
int b =(int) (a);
printf("b = %d\n", b);
}
The value of b should be 2
but I get the following output- b的值应为
2
但我得到以下输出-
a = 3.000000
b = 2
Why is it so? 为什么会这样呢?
If you change 如果你改变
printf("a = %f\n",a );
to 至
printf("a = %.20f\n",a );
it outputs 它输出
a = 2.99999952316284179688
As you can see this is not 3. 如您所见,这不是3。
So the conversion truncates it to 2. 因此,转换将其截断为2。
When a float is converted to int only the integer part is stored ie 2.9 only 2 is stored and remaining is truncated. 当浮点数转换为int时,仅存储整数部分,即2.9仅存储2,其余部分被截断。 Similar one in the case of division
分割时类似
#include<stdio.h>
main()
{
int a=12/5;
printf("%d\n",a);
}
Here the result is 2.4 but .4 is truncated .. 这里的结果是2.4,但是.4被截断了..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.