将int转换为float

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.您可以转换为float (更好的double )或乘以100.0 (对于double精度, float精度为100.0f ),

 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相同),但它几乎不可能影响小数点后的前两位因此,选择哪种方式可能无关紧要。

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

如果您想获得所需的结果,请尝试以下方法:

 ((float)number/total)*100 

要么

 50.0/100 

不,因为你使用整数表达式,所以你将整数 50除以整数 100,得到整数 0.键入将其中一个转换为float ,它应该有效。

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

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

顺便说一句, %f期望double而非float 。 通过在这里转换的纯粹运气,它运作良好。 但是现在通常你在C中大多使用double浮点类型。

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

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

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

将您的代码更改为:

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

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