Alex Rivera | Logout

How to convert int to float in C?

Asked 2012-11-23T13:34:43.737
30

I am trying to solve:

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

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

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.

c int
Edit
Report

1 Answer

11

integer division in C truncates the result so 50/100 will give you 0

If you want to get the desired result try this :

((float)number/total)*100

or

50.0/100
answered 2012-11-23T13:40:03.310

Your Answer