# Thread: This HAS to be some stupid error on my part..

1. ## This HAS to be some stupid error on my part..

Well I excerpted as much as possible to make it easier to determine the problem, and I'm sure it's something really simple, but I just started programming a week ago and I'm just trying to learn one problem at a time, and this one has me stumped

Code:
```#include <iostream>

using namespace std;

int main()
{
int possible [10];
int total [10];

possible [1] = 5;
total [1] = 7;

cout<<possible [1] / total [1] * 100;
cin.get();
}```
Why won't it give me a percentage? It outputs 100 if both arrays are set to 1, but any other combination yeilds 0. And it's kind of important that I use arrays here.. Can anyone help?

2. Because you're using integer math.

5/7 = 0 in integer math.

You need to either make your arrays floating-point types, or cast them to floating-point types before the division.

Or, you could do the multiplication first and then the division, as long as you're aware that, for example, 67.99% would round down to 67%.

3. It was THAT easy.. Thanks!

4. When you divide an integer by an integer, the return value is an integer as well. So you need to change the type of a variable (in this case, to a float) when you're dividing two variables.

Code:
`cout << static_cast<float>(possible [1]) / total [1] * 100;`
Also, though multiplication and division are supposed to be equal in terms of precedence you'll get the following result if you don't bracket it correctly:

Code:
`possible / (total * 100)`
You need to explicitly bracket it as:
Code:
`cout << (static_cast<float>(possible [1]) / total [1]) * 100;`

5. Don't do all that casting. Make the variables floats in the first place.

6. Let me suggest double, instead. Float in my opinion should only be used on those cases where there is a real intention of limiting precision. With only 6 digits of guaranteed precision, float is usually too small for most operations.

Popular pages Recent additions