将int转换为float

Jac*_*ack 17 c int

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

percentage=(number/total)*100;
printf("%.2f",percentage);
Run Code Online (Sandbox Code Playgroud)

如果数字的值是50并且总数是100,那么我应该得到50.00的百分比,至少这是我想要的.但我一直得到0.00作为答案,并尝试了很多类型的变化,但无济于事.

Dan*_*her 27

整数除法截断,所以(50/100)在0的结果可以转换为float(更好double)或乘100.0(用于double精密,100.0f对于float精度)第一,

double percentage;
// ...
percentage = 100.0*number/total;
// percentage = (double)number/total * 100;
Run Code Online (Sandbox Code Playgroud)

要么

float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;
Run Code Online (Sandbox Code Playgroud)

由于浮点运算是不相关的,结果100.0*number/total(double)number/total * 100可能略有不同(同样适用float),但它绝对不可能的影响小数点后的头两个地方,所以它可能不会不管你选择哪种方式.


Omk*_*ant 6

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

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

((float)number/total)*100
Run Code Online (Sandbox Code Playgroud)

要么

50.0/100
Run Code Online (Sandbox Code Playgroud)