Hello everyone. I started learning C++ a few days ago. I have a problem. I am trying to calculate the percentage using the code below. But it's giving me a zero. I don't understand what I have done wrong. I have gone through the code many times.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int main()
{
int a = 10; int b = 100;
int per = (a/b) * 100;
cout << "Percentage is : " << per << endl;
return 0;
}
Shouldn't this code give me "Percentage is : 10"?
Would really appreciate it if someone would help. :)
#include <iostream>
usingnamespace std;
int main()
{
int a = 10; int b = 100;
double per = (double)(a/b) * 100;
cout << "Percentage is : " << per << endl;
return 0;
}
Just out of curiosity - wouldn't it suffice to cast just one of the two operands to double?
Won't the "lowest" type (int) be converted to the highest (float) if you do:
float per = static_cast<float>(a)/b*100
Just asking out of interest what the preferred way of doing this is :)