c - 解释将Float转换为整数时的输出?

标签 c gcc type-conversion

<分区>

我完全不知道输出是怎么来的

    float f=1.4, t;
    int d,s;

    d=(int)f;
    printf("d=%d\n",d);
    t=f-d;
    printf("t=%f\n",t);
    t=t*10;
    printf("t=%f\n",t);
    s=(int)t;
    printf("s=%d\n",s);

输出是

d=1
t=0.400000
t=4.000000
s=3

f=1.1

时类似

输出是

d=1
t=0.100000
t=1.000000
s=1

这是否与整数和 float 在内存中的存储方式或其他方式有关?

最佳答案

你已经初始化了 f=1.4,而不是当你这样做的时候

    d=(int)f;

您正在将 float 转换为整数,当 float 转换为整数时,句点“.”之后的所有数字。被截断。现在 d 有 1 所以

    t=f-d;

将是 1.4 - 1 = 0.4

    t=t*10;

t=0.4*10=4 因为 t 是 float 所以它输出 4.0000

float 表示最后的尾随零

    s=(int)t;

这里你再次将 float 转换为整数,现在这是棘手的部分,上面的所有值都四舍五入,这里 t 的值为 3.99999976 所以当转换为整数时它显示 3

这都是因为当你初始化t=1.4时,实际上它被初始化为1.39999998

关于c - 解释将Float转换为整数时的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21503888/

相关文章:

C 将十六进制值添加到字符串,没有库

c - 带有用户输入的二维数组

c++ - gcc:如何正确使用 __attribute((__may_alias__)) 以避免 "derefencing type-punned pointer"警告

python - gcc 编译器无法识别 -fno-plt 选项

gcc - GNU 可以在汇编文件(.s)中作为过程结构和函数原型(prototype)吗?

c++ - '消息框A' : cannot convert parameter 2 from 'std::vector<_Ty>' to 'LPCSTR'

java 转换整数以通过网络发送

c - 我不明白简单得可笑的 MPI_Send/Recv 问题

function - Go 是否支持函数的类型转换/类型转换?

从 uint16 到 uint8 的转换