Problem with calculating Percentage

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>

using namespace 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. :)
Last edited on
a/b=0.10 but as per is integer so it changes to 0.and 0*100 = 0.

Use

double per = (double)(a/b) * 100;
Hey thanks ALOT! Does the double mean it's upto 2 decimal place or something?
double is 8 byte in size and stores double the no of decimal places then float...um maybe about 16.You can use float instead of double to save memory.

int is 2 byte in size.
Using this code, it still gives me 0. :/

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
{
    int a = 10;  int b = 100;
    double per = (double)(a/b) * 100;
    cout << "Percentage is : " << per << endl;
    return 0;
}
@Akshit
The byte sizes depends on the platform/compiler. int is at least 2 bytes but is nowadays often 4 bytes.
Last edited on
I was talking about mostly used VC++.But yes you are true.
@Dodu

My mistake.Use it like this

double per = ((double)a/(double)b) * 100;

or

float per = ((float)a/(float)b) * 100;
Last edited on
or declare all variable as double or float.
closed account (o3hC5Di1)
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 :)

All the best,
NwN
Last edited on
@NwN
Yes you are right. Only one cast is needed.
@Akshit


Thank you! :)
Topic archived. No new replies allowed.