Reputation: 6549
I'm using the following code to calculate and display the final score for a math game in C++.
int score = (correctNumber / 3) * 100;
cout << score;
The variable "correctNumber" is always a value between 0 and 3. However, unless "correctNumber" = 3, then the variable "score" always equals "0". When "correctNumber" equals 3 then "score" equals 100.
Say "correctNumber" was equal to 2. Shouldn't "score" be 67 then? Is this some issue with int variable type being unable to calculate decimal points?
Upvotes: 1
Views: 204
Reputation: 10378
The problem is that (correctNumber / 3)
is an integer, so you can't get 0.666 or any fraction to multiply by 100, which what I believe is you want.
You could try to force it to be a float
like this:
int score = ((float)correctNumber / 3) * 100;
This, however, will give you 66 instead of 67, cause it doesn't round up. You could use C99 round()
for that.
int score = round(((float)correctNumber / 3) * 100);
UPDATE:
You can also use + 0.5
to round, like this:
int score = (correctNumber / 3.0f) * 100.0f + 0.5f;
Upvotes: 1
Reputation: 61970
I'm assuming correctNumber
is an int
, based on what you described. What's happening is integer truncation. When you divide an int
by an int
, the result always rounds down:
1/3 = 0.3333 = 0 as an integer
2/3 = 0.6667 = 0 as an integer
3/3 = 1.0000 = 1 as an integer
The easy way to remedy this here is to multiply it first:
int score = correctNumber * 100 / 3;
However, this still leaves you with 66 for 2, not 67. A clear and simple way of dealing with that (and many other rounding situations, though the rounding style is unconfigurable) is std::round
, included since C++11:
int score = std::round(currentNumber * 100. / 3);
In the example, the dot in 100.
makes 100
a double
(it's the same thing as 100.0
), so the result of the operation will be the floating-point value you want, not a pre-truncated value passed in as a floating-point value. That means you'll end up with 66.66666... going into std::round
instead of 66.
Upvotes: 4
Reputation: 15834
Your guess is correct. int
can't store real numbers.
But you can multiply first, and then divide, like
score = correctNumber * 100 / 3;
score will have 0, 33, 66, 100, depending on values of correctNumber
Upvotes: 2
Reputation: 40887
You are doing math as integer so 1 / 3 is 0.
Try:
int score = (100 * correctNumber) / 3
and if you want to round:
int score = (100 * correctNumber + 1) / 3
Upvotes: 7