How to convert int to float in C?

后端 未结 9 726
花落未央
花落未央 2020-12-03 07:38

I am trying to solve:

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

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

If the val

相关标签:
9条回答
  • 2020-12-03 07:55

    Integer division truncates, so (50/100) results in 0. You can cast to float (better double) or multiply with 100.0 (for double precision, 100.0f for float precision) first,

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

    or

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

    Since floating point arithmetic is not associative, the results of 100.0*number/total and (double)number/total * 100 may be slightly different (the same holds for float), but it's extremely unlikely to influence the first two places after the decimal point, so it probably doesn't matter which way you choose.

    0 讨论(0)
  • 2020-12-03 07:56

    You are doing integer arithmetic, so there the result is correct. Try

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

    BTW the %f expects a double not a float. By pure luck that is converted here, so it works out well. But generally you'd mostly use double as floating point type in C nowadays.

    0 讨论(0)
  • 2020-12-03 08:02

    integer division in C truncates the result so 50/100 will give you 0

    If you want to get the desired result try this :

    ((float)number/total)*100
    

    or

    50.0/100
    
    0 讨论(0)
  • 2020-12-03 08:02

    No, because you do the expression using integers, so you divide the integer 50 by the integer 100, which results in the integer 0. Type cast one of them to a float and it should work.

    0 讨论(0)
  • 2020-12-03 08:05

    Change your code to:

    int total=0, number=0;
    float percentage=0.0f;
    
    percentage=((float)number/total)*100f;
    printf("%.2f", (double)percentage);
    
    0 讨论(0)
  • 2020-12-03 08:11

    I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.

    0 讨论(0)
提交回复
热议问题