【问题标题】:Simpliest operation in C not working [duplicate]C中最简单的操作不起作用[重复]
【发布时间】:2011-09-10 03:30:30
【问题描述】:

可能的重复:
Possible Loss of Fraction
What is the behavior of integer division in C?

我是 C 新手,遇到了一些麻烦。以下代码:

int nr = 3;
float fl = nr/10;
printf("%4.1f\n", fl);

按我的预期打印0.0 但不是0.3。有什么问题?

【问题讨论】:

  • @Ólafur:我不认为有关特定 C# 警告消息的问题与有关 C 中整数除法的问题真正重复。
  • 这是同一个问题,他正在划分两个整数并失去精度。链接的问题中有很好的解释。

标签: c floating-point


【解决方案1】:

nr 是一个 int,因此您仍在进行整数除法,但将其分配给浮点数。将nr 转换为浮点数:

float fl = (float) nr / 10;
// or divide by a float
float fl = nr / 10.0f;

【讨论】:

    【解决方案2】:

    一个整数除以一个数字将是一个向下舍入的整数。您需要先将 nr 转换为浮点数...

    float fl = (float) nr /10;
    

    或者通过将分母也设为浮点数来让编译器知道你想要浮点数

    float fl = nr /10.0f;
    

    【讨论】:

    • 截断是正确的词:-P
    • 截断可能是正确的词,但对于新手来说,我认为更常见的措辞会更有帮助。
    【解决方案3】:

    这个:

    float fl = nr/10;
    

    进行整数运算。你想要:

    float fl = nr/10.0;
    

    此外,除非您有特定的理由不这样做,否则最好对浮点活动使用双精度数,而不是浮点数。

    【讨论】:

      【解决方案4】:

      试试

      float fl = (float)nr / 10;
      

      否则编译器将进行整数运算。 c faq on the subject 很棒。

      【讨论】:

        【解决方案5】:
        int nr = 3;
        float fl = nr/10; // float = int/int => integer division and then conversion to float
        printf("%4.1f\n", fl);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-14
          • 1970-01-01
          • 1970-01-01
          • 2013-11-07
          • 2018-03-10
          • 2012-06-07
          相关资源
          最近更新 更多