0

I'm new to C++ and working on this lab:

Write a program that asks the user to enter a number of quarters, dimes, nickels and pennies and then outputs the monetary value of the coins in the format of dollars and remaining cents.

The example given:

Please enter the number of coins:

  • # of quarters: 20
  • # of dimes: 4
  • # of nickels: 13
  • # of pennies: 17

The total is 6 dollars and 22 cents

Here's the code I initially used:

#include <iostream>
using namespace std;

int main() {
    
    int quarters, dimes, nickels, pennies, dollars, cents;
    double total;

    cout<<"Please enter the number of coins"<<endl;
    cout<<"# of quarters:"<<endl;
    cin>>quarters;
    cout<<"# of dimes"<<endl;
    cin>>dimes;
    cout<<"# of nickels"<<endl;
    cin>>nickels;
    cout<<"# of pennies"<<endl;
    cin>>pennies;

    total = quarters * .25 + dimes * .10 + nickels * .05 + pennies * .01;
    dollars = (int)total;
    cents = (total - dollars) * 100;

    cout<<"The total is "<<dollars<<" dollars and "<<cents<<" cents."<<endl;

    return 0;
}

       

But it kept returning 6 dollars and 21 cents. I eventually guessed and changed cents to a double and that solved it, but I'm still unsure why the first solution didn't work. I think? it has something to do with how the variables are cast, but again, that's just a guess. Any help would be great!

  • 2
    `double`s [are imprecise](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) and should not be used for computations involving money. People get really weird when rounding doesn't go in their favour. – user4581301 Jun 25 '21 at 20:22
  • When I run this I get `total` of 6.2200000000000006. By the whim of the gods you could get 6.2199999999999999 which will truncate and drop a penny. – user4581301 Jun 25 '21 at 20:28
  • 2
    Multiply your input by 100 and work with integral pennies (cents). Stay away from floating point. – Thomas Matthews Jun 25 '21 at 20:29
  • Thanks, y'all. I changed the original to handle it all through integers and got rid of the total variable completely. – undercoverk3vin Jun 25 '21 at 20:38
  • 1
    Extra reading: [Fixed Point Arithmetic](https://en.wikipedia.org/wiki/Fixed-point_arithmetic). – user4581301 Jun 25 '21 at 20:40

0 Answers0