Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get percent of number in c++

How can I calculate several percent of int?
for example I want to get 30% from number, if I will use this example of code, I will get wrong answer:

int number = 250;
int result = (number / 100) * 30;  

result will be 60, and the real answer is 75, is there any way to calculate it?

like image 801
user1544067 Avatar asked Jul 01 '13 13:07

user1544067


4 Answers

Multiply before dividing:

int result = number * 30 / 100;

The reason you get the result you get is that division with integer types produces an integer result: 250 / 100 is 2. If you multiply before dividing you still get an integer result, but at least you haven't lost data in intermediate steps. If you have to deal with really huge numbers there is a danger of overflowing the range permitted by int though.

Alternatively you can use floating point arithmetic, where division can produce fractions of integers:

int result = number * 0.30;

This may produce unexpected results though, so you're better off using integers only as above. Or write 3.0/10 instead of 0.30.

like image 130
Joni Avatar answered Sep 22 '22 21:09

Joni


Switching the operands (as others suggested) would work too, but just in case you do not want to, there's another solution:

int number = 250;
int result = static_cast<double>(number) / 100 * 30; 
like image 34
Sceptical Jule Avatar answered Sep 22 '22 21:09

Sceptical Jule


Assuming the numbers are small(ish), you can just turn it around:

 int result = (number * 30) / 100;

(Parenthesis not required, but helps clarify).

This won't work if either of the numbers are several million, but should be fine for numbers smaller than that.

like image 22
Mats Petersson Avatar answered Sep 23 '22 21:09

Mats Petersson


Try this,

int number = 250;
float result = number  * (float)(30/100.0);
like image 37
CodeCrusader Avatar answered Sep 22 '22 21:09

CodeCrusader