Home > Software design >  Calculate amount of coins
Calculate amount of coins

Time:09-26

I have the assignment from ZyLab

Given six values representing counts of silver dollars, half dollars, quarters, dimes, nickels, and pennies, output the total amount as dollars and cents. The variable totalAmount is used to represent the total amount of money.

Output each floating-point value with two digits after the decimal point, which can be achieved by executing results once before all other cout statements.

Ex: If the input is: 5 3 4 3 2 1

where 5 is the number of silver dollars, 3 is the number of half-dollars, 4 is the number of quarters, 3 is the number of dimes, 2 is the number of nickels, and 1 is the number of pennies, the output is: Amount: $5.66

For simplicity, assume input is non-negative.

Here is my code:

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    double totalAmount;
    int dollars;
    int halfDollars;
    int quarters;
    int dimes;
    int nickels;
    int pennies;

    /* Type your code here. */
    /* get input */
    cin >> dollars;
    cin >> halfDollars;
    cin >> quarters;
    cin >> dimes;
    cin >> nickels;
    cin >> pennies;

    /* calculate totalAmount */
    cout << fixed << setprecision(2);
    halfDollars = halfDollars * 0.5;
    quarters = quarters * 0.25;
    dimes = dimes * 0.10;
    nickels = nickels * 0.05;
    pennies = pennies * 0.01;
    totalAmount = dollars   halfDollars   quarters   dimes   nickels   pennies;
    /* output results */
    cout << "Amount: " << totalAmount << endl;
    return 0;
}

What is wrong?

CodePudding user response:

Your variables should be of type float.

Rewrite your code as following:

float dollars;
float halfDollars;
float quarters;
float dimes;
float nickels;
float pennies;

When you are converting for example half dollars, 3 half dollars * 0.5 is 1.5, but it can't be stored inside integer variable, so you need the variable to be of type float.

So when compiler is executing this piece of code;

/* calculate totalAmount */
cout << fixed << setprecision(2);
halfDollars = halfDollars * 0.5;
quarters = quarters * 0.25;
dimes = dimes * 0.10;
nickels = nickels * 0.05;
pennies = pennies * 0.01;

it stores floating point value inside an integer declared variable, so compiler naturally casts it to integer type, producing incorrect output.

  •  Tags:  
  • c
  • Related