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!