【问题标题】:Explain the output when converting Float to integer? [duplicate]解释将浮点数转换为整数时的输出? [复制]
【发布时间】:2014-02-25 13:17:17
【问题描述】:

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

    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

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

【问题讨论】:

  • 不,不是!你们不能谷歌“浮点运算意外结果”,你能...>。
  • @H2CO3 请向谷歌表示敬意,然后发布您的答案...谢谢您这么有礼貌:)

标签: c gcc type-conversion


【解决方案1】:

让我们一步一步来看看浮点数和int 是如何交互的。

假设一个典型的平台,其中
floatIEEE 754 single-precision binary floating-point format 并且
doubleIEEE 754 double-precision binary floating-point format

float f=1.4, t;
// 1.4 isn't exactly representable in FP & takes on the closest `double` value of
// 1.399999999999999911182158029987476766109466552734375
// which when assigned to a float becomes 
// 1.39999997615814208984375

int d,s;
d=(int)f;
// d gets the truncated value of 1 and prints 1, no surprise.
printf("d=%d\n",d);

t=f-d;
// t gets the value 0.39999997615814208984375
// A (double) version of t, with the same value is passed to printf()
// This is printed out, rounded to 6 (default) decimal places after the '.' as 
// 0.400000
printf("t=%f\n",t);

t=t*10;
// t is multiplied by exactly 10 and gets the value
// 3.9999997615814208984375
// A (double) version of t, with the same value is passed to printf()
// which prints out, rounded to 6 decimal places after the '.' as 
// 4.00000.
printf("t=%f\n",t);

s=(int)t;
// s gets the truncated value of 3.9999997615814208984375
// which is 3 and prints out 3. - A bit of a surprise.
printf("s=%d\n",s);

【讨论】:

    【解决方案2】:

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

        d=(int)f;
    

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

        t=f-d;
    

    将是 1.4 - 1 = 0.4

        t=t*10;
    

    t=0.4*10=4 并且因为 t 是浮点数,所以它输出 4.0000

    浮点数表示末尾的尾随零

        s=(int)t;
    

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

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

    【讨论】:

      【解决方案3】:

      在第一次分配期间

      float f=1.4;
      

      有一个近似值,因为 1.4 旨在作为双精度(不是浮点数)。 1.39999999 之类的东西被分配给 f。

      尝试使用

      float f=1.4f;
      

      它应该可以按您的预期工作。

      【讨论】:

      • 还需要说明的是,printf首先转换为double(因为它是一个可变参数函数),然后对打印的内容进行四舍五入,这就是它显示1.400000的原因
      • @ooga printf 在这种情况下什么都不做。由于我描述的近似值,s 包含 3。
      • 但是当他打印 t (浮点数)时,它会在调用和 printf 轮之前转换为 double。
      • @ooga 你是对的,现在我明白你的意思了。
      猜你喜欢
      • 2018-06-26
      • 1970-01-01
      • 2020-04-29
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多