【问题标题】:How to convert int to float in C?如何在C中将int转换为float?
【发布时间】:2012-11-11 21:14:34
【问题描述】:

我正在尝试解决:

int total=0, number=0;
float percentage=0.0;

percentage=(number/total)*100;
printf("%.2f", percentage);

如果数字的值是 50 并且总数是 100,我应该得到 50.00 的百分比,这就是我想要的。但我一直得到 0.00 作为答案,并尝试了对类型的许多更改,但没有奏效。

【问题讨论】:

  • 因为 50/100 (= 0.5) 的 int 部分是 0

标签: c int


【解决方案1】:

这可以给你正确的答案

#include <stdio.h>
int main()
{
    float total=100, number=50;
    float percentage;
    percentage=(number/total)*100;
    printf("%0.2f",percentage);
    return 0;
}

【讨论】:

    【解决方案2】:

    如果我想要浮点数,我通常会乘以 1.0,这比记住规则要容易。

    【讨论】:

      【解决方案3】:

      整数除法会被截断,因此(50/100) 的结果为 0。您可以转换为 float(更好的 double)或乘以 100.0(对于 double 精度,100.0f 对于 float 精度)首先,

      double percentage;
      // ...
      percentage = 100.0*number/total;
      // percentage = (double)number/total * 100;
      

      float percentage;
      // ...
      percentage = (float)number/total * 100;
      // percentage = 100.0f*number/total;
      

      由于浮点运算不是关联的,100.0*number/total(double)number/total * 100 的结果可能会略有不同(float 也是如此),但极不可能影响小数点后的前两位,所以你选择哪种方式可能并不重要。

      【讨论】:

      • 前者双精度计算,后者单精度计算。所以它们可能不等价。使用 100.0f 获取浮点文字。
      【解决方案4】:

      将您的代码更改为:

      int total=0, number=0;
      float percentage=0.0f;
      
      percentage=((float)number/total)*100f;
      printf("%.2f", (double)percentage);
      

      【讨论】:

        【解决方案5】:

        这应该会给你想要的结果。

        double total = 0;
        int number = 0;
        float percentage = number / total * 100
        printf("%.2f",percentage);
        

        注意第一个操作数是双精度数

        【讨论】:

          【解决方案6】:

          C 中的整数除法会截断结果,因此50/100 将给您0

          如果你想得到想要的结果,试试这个:

          ((float)number/total)*100
          

          50.0/100
          

          【讨论】:

            【解决方案7】:

            你正在做整数运算,所以结果是正确的。试试

            percentage=((double)number/total)*100;
            

            顺便说一句,%f 期望 double 而不是 float。纯粹靠运气在这里转换,所以效果很好。但一般来说,现在你主要使用double 作为 C 中的浮点类型。

            【讨论】:

              【解决方案8】:

              不,因为您使用整数进行表达式,所以您将 integer 50 除以 integer 100,得到 integer 0. 将其中一个类型转换为float,它应该可以工作。

              【讨论】:

                猜你喜欢
                • 2011-11-02
                • 2017-09-04
                • 1970-01-01
                • 1970-01-01
                • 2011-07-11
                • 2021-07-07
                • 1970-01-01
                • 2021-10-12
                • 2019-12-04
                相关资源
                最近更新 更多