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.
This Should work Making it Round to 2 Point
int a=53214
parseFloat(Math.round(a* 100) / 100).toFixed(2);
This can give you the correct Answer
#include <stdio.h>
int main()
{
float total=100, number=50;
float percentage;
percentage=(number/total)*100;
printf("%0.2f",percentage);
return 0;
}
This should give you the result you want.
double total = 0;
int number = 0;
float percentage = number / total * 100
printf("%.2f",percentage);
Note that the first operand is a double
I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.
Change your code to:
int total=0, number=0;
float percentage=0.0f;
percentage=((float)number/total)*100f;
printf("%.2f", (double)percentage);
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
You are doing integer arithmetic, so there the result is correct. Try
percentage=((double)number/total)*100;
BTW the %f
expects a double
not a float
. By pure luck that is converted here, so it works out well. But generally you'd mostly use double
as floating point type in C nowadays.
No, because you do the expression using integers, so you divide the integer 50 by the integer 100, which results in the integer 0. Type cast one of them to a float
and it should work.
Source: Stackoverflow.com