Reputation: 17
I am wondering why my code isn't displaying the amount in cents and only displaying the amount in dollars. Anyone see where I am going wrong?
int dollars;
int change;
int quarters;
int dimes;
int nickels;
int pennies;
cout << "Enter amount of quaters" << endl;
cin >> quarters;
cout << "Enter amount of dimes" << endl;
cin >> dimes;
cout << "Enter amount of nickels" << endl;
cin >> nickels;
cout << "Enter amount of pennies" << endl;
cin >> pennies;
quarters = quarters * 0.25;
dimes = dimes * 0.10;
nickels = nickels * 0.05;
pennies = pennies * 0.01;
dollars = quarters + dimes + nickels + pennies;
change = dollars % quarters + dimes + nickels + pennies;
cout << "You have " << dollars << " dollar(s)" << endl;
cout << "You have " << change << " cents" << endl;
return 0;
}
Upvotes: 1
Views: 4020
Reputation: 10770
Doing dimes = dimes * 0.10;
, dimes
is still an int
and cannot represent fractional amounts. You will want to store them in a float
instead.
Here's an example:
int dimes_int = 2;
float dimes_float = dimes_int * 0.1;
dimes_int = dimes_float;//convert the floating point number to an integer.
std::cout << dimes_float << ' ' << dimes_int << '\n';
You should get 0.2 0
as your output.
For more serious finance calculations, there are lots of difficulties using floating point types with roundoff errors, but I suspect in your case this isn't a big deal.
Upvotes: 2