user1544067 - 7 months ago 27

C++ Question

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`

`75`

Answer

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`

.