如何在C中将int转换为float? [英] How to convert int to float in C?
问题描述
我正在尝试解决:
int total=0, number=0;
float percentage=0.0;
percentage=(number/total)*100;
printf("%.2f", percentage);
如果数字的值为50,而总数为100,我应该得到50.00的百分比,这就是我想要的.但是我一直得到0.00作为答案,并尝试了对类型的许多更改,但是它们没有用.
If the value of the number is 50 and the total is 100, I should get 50.00 as percentage and that is what I want. But I keep getting 0.00 as the answer and tried many changes to the types but they didn't work.
推荐答案
整数除法会被截断,因此(50/100)
的结果为0.您可以强制转换为float
(更好的double
)或与100.0
相乘(对于double
精度,100.0f
表示float
精度)
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;
或
float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;
由于浮点运算没有关联性,因此100.0*number/total
和(double)number/total * 100
的结果可能会略有不同(float
的结果相同),但极不可能影响小数点后的前两位,因此选择哪种方式都可能无关紧要.
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.
这篇关于如何在C中将int转换为float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!