如何在C语言中将整型转换为浮点型?

29

我正在尝试解决:

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

percentage=(number/total)*100;
printf("%.2f", percentage);
如果数字的值为50,总数为100,则我应该得到50.00作为百分比,这正是我想要的。但是我一直得到0.00作为答案,并尝试了许多类型的更改,但它们都没有起作用。

1
因为50/100的int部分(=0.5)是0。 - Michaël
11个回答

0

顺序很重要。你不能在表达式中随便放一个双精度数。解析器必须在进行任何整数运算之前遇到它。

int obs, tot;
float percent;
obs = 17;
tot = 40;
printf("%f\n",
        percent = obs / tot * 100);
printf("%f\n",
        percent = obs / tot * 100.0);
printf("%f\n",
        percent = 100.0 * obs / tot);
printf("%f\n",
        percent = obs*100.0/ tot);
printf("%f\n",
        percent = 100.0* (obs / tot) );

输出结果:

0.000000
0.000000
42.500000
42.500000
0.000000

所以双精度浮点数必须出现在要执行的第一个操作中。第三和第四种方法可以正常工作,但请注意,括号可以优先考虑整数除法,因此第五种方法失败。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接