转换INT浮动 [英] Convert int to float

查看:145
本文介绍了转换INT浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 number is 50 and total is 100, I should get 50.00 for percentage, at least that is what I want. but I keep getting 0.00 as the answer and tried many changes to the types as well but no avail.

推荐答案

整数除法截断,所以(50/100)的结果为0,您可以转换为浮动(更好的双击)或 100.0 (为<$乘C $ C>双击 precision, 100.0f 浮动 precision)第一,

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 *数/总(双)数/总* 100 可能会略有不同(同样适用于浮动),但它是极不可能影响到小数点后的第一个两地,所以它可能不无论你选择哪种方式。

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.

这篇关于转换INT浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆