Home Ask Login Register

Developers Planet

Your answer is one click away!

Sayed Alesawy February 2016

C++ , A code to get an amount of money to convert into quarters, dimes , nickels, pennies

THE CODE IS NOT WORKING PROPERLY !! I am newbee to C++ and my assignment to write a code that takes a value from the user ( amount of money ) and then convert it into " quarters = 25 cents , dimes = 10 cents , nickels = 5 cents and pennies = 1 cent " so for example when i enter the value 7.47 i should get 29 quarter , 2 dimes , 0 nickels , 2 pennies and so on ... my problem is that i have tried many values and it work just fine , but when i tried the value 9.53 i should get 38 quarters , 0 dimes , 0 nickels and 3 pennies BUT instead i get 38 quarters , 0 dimes , 0 nickels and 2 pennies the same error happens when i try 8.53 , but when i try 6.53 ,5.53 .4.53 it works well !! i am so confused now , so please help !!

`#include<iostream>
using namespace std;
int main()
{
    double money, c_money, quarters, dimes, nickels, pennies, remainder; char response; 
    new_input:                                      
    cout << " Enter the amount of money to be converted : " << endl;
    cin >> money;
    while (money < 0)
    {                                                                               
        cout << " Invalid input , please enter a non-negative value " << endl;      
        cin >> money;
    }
    c_money = money * 100;                                              
    quarters = (int)c_money / 25;
    remainder = (int)c_money % 25;
    dimes = (int)remainder / 10;
    remainder = (int)remainder % 10;
    nickels = (int)remainder /5;
    remainder = (int)remainder % 5;
    pennies = (int)remainder ;
    cout << endl;
    cout << " The amount of money entered could be represented as : " << endl;
    cout << "*****************************************************" << endl;
    cout <<" Number of quarters : "<< quarters << endl;
    cout <<" Number of dimes    : "<<dimes << endl;
    cout <<" Number of nickels  : "<&        

Answers


radoh February 2016

You are a victim of double inaccuracy. Your code may work in 99% cases, but the inaccuracy comes in the remaining 1%...

I suggest you don't use double when you need to make exact calculations, e.g. concerning money where every penny counts. You will be better of by replacing it with int, multiplying it by 100 (so you don't lose the decimal part) and do all calculations with integers.

Post Status

Asked in February 2016
Viewed 2,892 times
Voted 11
Answered 1 times

Search




Leave an answer


Quote of the day: live life