+ 1

Code Coach - Kaleidoscopes

I can't seem to figure out why my coding is failing on the last two tests :( It passes the first three by correctly rounding the number to two decimal places, but the last two tests are hidden and do not show the input or output. Here is what I have (I've been trying to round the number different ways and commenting them out): #include <iostream> #include <iomanip> using namespace std; float round(float total) { float value = (int)(total * 100 + .5); return (float)value / 100; } const float scopeCost = 5.00; const float scopeDiscount = 0.10; const float scopeTax = 0.07; int main() { int scopeBuy; float total; cin >> scopeBuy; total = scopeBuy * scopeCost; if(scopeBuy > 1){ total = total - (scopeDiscount * total); }; total = total + (scopeTax * total); //cout << std::fixed << std::setprecision(2) >> total; printf("%.2f", round(total)); //cout << round(total); return 0; }

8th Sep 2020, 9:55 PM
Ace33
Ace33 - avatar
4 Antworten
+ 8
Yeah, those are some nasty floating point imprecision issues. I remember that straightup printing everything in one big equation helped for me, i.e. std::cout << std::fixed << std::setprecision( 2 ) << ( a * 5 * 1.07 * ( a > 1 ? 0.9 : 1 ) );
8th Sep 2020, 10:14 PM
Shadow
Shadow - avatar
+ 3
I greatly appreciate the explanation Coder Kitten! I was quite confused what was going on and it was hard to tell since it was hiding the input and output :( I can definitely see how calculating the problem in cents would make the long decimal values alot easier to deal with and will keep that in mind when it comes to calculating currency in the future!
9th Sep 2020, 8:33 AM
Ace33
Ace33 - avatar
+ 2
Thank you Shadow, this work perfectly! And it also made the code surprisingly simpler then what I had came up with 😄 I was googling trying all kinds of things determined to get the numbers to round the correct way.
9th Sep 2020, 8:23 AM
Ace33
Ace33 - avatar