While I was trying to practice C++, I got an interesting result from a simple calculation. I'm trying to calculate the decrease of how many carrots have been eaten in percentage. The input I gave was:
Current carrots = 27
Carrots eaten = 7
and the result should be 25,92%, but instead I got 847861444%. I don't understand why. If I calculate the same way I did in the program with a calculator then I get the desired result, which is 25,92%.
#include <iostream>
usingnamespace std;
int main()
{
int currentcarrots;
int carrotseaten;
cout << "How many carrots do you currently have? ";
cin >> currentcarrots;
cout << endl;
cout << "How many carrots will you eat? ";
cin >> carrotseaten;
cout << endl;
int result = (((currentcarrots - (currentcarrots - carrotseaten))/currentcarrots)*100);
cout << "The total amount of carrots you had to begin with was: "
<< currentcarrots
<< " and now you have "
<< currentcarrots - carrotseaten
<< ". That's a "
<< result
<< "% decrease.";
return 0;
}
Also, I'm not sure how to make this code smaller. If you know how to, could you please post the smaller code?
It's because the values involved are integers so it will do integer division which means the result of the division will be an integer (the decimal part is simply lost).
1 2 3 4 5 6
(((currentcarrots - (currentcarrots - carrotseaten))/currentcarrots)*100)
(((27 - (27 - 7))/27)*100)
(((27 - 20)/27)*100)
((7/27)*100) // 7 and 27 are integers so the division gives an integer.
(0*100)
0
To solve this you can add a cast so that at least one of the operands to the division operator is of a floating point type, or you could multiply by 100 before dividing instead of after. If you want the percent value to contain decimals you should go for the casting, and you will also have to change the type of the result variable.
I searched on Stackoverflow and I found out that the best thing to do would be to use:
static_cast<float>(variable)
I tried to do this:
int result = (((static_cast<float>(currentcarrots - (currentcarrots - carrotseaten))/currentcarrots))*100);
and it gave me the correct result, 25%. However, I'd like to get the decimals in there as well. Have I misplaced the cast or is there something I'm missing?