I have a program that takes in a cash amount in dollars and converts it to coins. Whenever the amount of pennies is over 1 the program output says that one less pennies than the actual amount is needed. For the amount to be inputed I first used a double. This is when the problem occured. I debugged the code and found that double was actually a hair smaller than the actual value. i.e (if the value is supposed to be 3.1 after calculations it will really be 3.09999999998) or something under the expected value. When the code computed amount of pennies it truncated the fractional part. But when using a float the actual value was just a hair over so the program ran correctly. Why is the value of so small a number not exact? Here is my code.
int main()
{
//must be set greater than a dollar for the while condition to run
float amount = 5.01; //Amount of money to be converted to q, d, n, and p's
cout << "Enter a dollar amount\n"
<< "less than $5.00\n";
while(amount >= 5.0)
{
cin >> amount;
/* data checking here... I just omitted the code
Everything is fine here */
}
int quarters = 0; //number of quarters, nickels, dimes, and pennies
int dimes = 0;
int nickels = 0;
int pennies = 0;
quarters = static_cast<int>(amount * 4);
amount = amount - (quarters * .25); /***************Problem code****/
dimes = static_cast<int>(amount * 10);
amount = amount - (dimes * .10); /***************Problem code****/
nickels = static_cast<int>(amount * 20);
amount = amount - (nickels * .05); /***************Problem code****/
pennies = static_cast<int>(amount * 100);
amount = amount - (pennies * .01); /***************Problem code****/
Where the problem code is marked the value of a double and float is not exact as it should be. amount either adds a few hundred-thousanths onto the number or subtracts it.
Decimal 0.1 is a recurring decimal in binary, which is the system floating point numbers use. That means that in order to precisely represent decimal 0.1 in binary, an infinite amount of space is required. Of course, the computer only has finite memory, so the representation is imprecise.
You may want to consider using an integer-based fixed point system: 1=1 cent, 100=$1, 1000=$10, etc.