-
Odd Error
Hello
This is a bit of a weird error, anyways..
I have a program which says how many quarters, nickels, etc.. you need out of the specified dollar figure.
When compiled in debug mode, w/ the dollar amount 1.91, everything works perfectly.
When compiled in release mode, w/ the dollar amount 1.91, everything works until it gets to pennies, it says 0.
I can't debug release mode obviously, so I have no idea what is wrong. I have deleted both the release folder and debug, and re-compiled both, each in a different order, and it still comes out the same way.
Any idea? Thanks.
-
-
#include <iostream>
using std::cout;
using std::endl;
using std::cin ;
int main()
{
float total = 0;
int data[6] = { 0, 0, 0, 0, 0, 0 };
cout << "\nHow much money? $";
cin >> total;
total *= 100;
for( total; total >= 100; )
{
total -= 100;
data[0]++;
}
for( total; total >= 50; )
{
total -= 50;
data[1]++;
}
for( total; total >= 25; )
{
total -= 25;
data[2]++;
}
for( total; total >= 10; )
{
total -= 10;
data[3]++;
}
for( total; total >= 5; )
{
total -= 5;
data[4]++;
}
for( total; total >= 1; )
{
total -= 1;
data[5]++;
}
cout << endl;
cout << "Silver Dollars: " << data[0] << endl;
cout << " Half Dollars: " << data[1] << endl;
cout << " Quarters: " << data[2] << endl;
cout << " Dimes: " << data[3] << endl;
cout << " Nickels: " << data[4] << endl;
cout << " Pennies: " << data[5] << endl;
cout << endl;
return 0;
}
-
Hmm, the code works for me.
Why not add a lot of extra cout's to document exactly what total is after each loop, and to document every entry into each loop. Maybe that will point out a problem.
-
Salem probably hit it on the head -- in binary, 91/100 is an infinite, repeating decimal. So you probably have rounding error causing this.
The alternative to Salem's string parsing idea is to do this:
Code:
float t = 0;
int total = 0;
int data[6] = { 0, 0, 0, 0, 0, 0 };
cout << "\nHow much money? $";
cin >> t;
total = (int)(t *100 +0.5);
And then use it from there. In this way, you read in a float, multiply by 100 and round to the nearest integer -- (int)(f + 0.5) will return f rounded to the nearest integer. This should work just fine, because floats should have enough precision that you're not going to be off by more than 0.5 cents.
Your problem is that the computer probably thinks you have something like 190.9999999 cents, not 191 cents exactly, so the 0.99999999 cents doesn't get counted as the last penny.