English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Im making a program where the user inputs a price, and it selects the correct change, 20's, 10's, 5s , 1's , quatrers , dimes , nickles , and pennies. Problem is once we get to pennies, i get crazy decimals... how do we fix this?

2007-04-10 02:37:49 · 4 answers · asked by Dustin B 1 in Computers & Internet Programming & Design

4 answers

When come the time to return the change, simply change your monetary unit from dollars to cents by multiplying everything by 100. From then you simply work with integer instead of float, and you don't have any rounding problem.

//lets say you have
float changeInDollars = 0.815;

// do the following, this will truncate the value into cents.
// Since float to int conversion use truncation not rounding
// add a 0.005 value to your value to make it truncate to 82 cents.
int changeInCents = 100*(changeInDollars + 0.005);

hope this help

2007-04-10 07:12:03 · answer #1 · answered by Rah-Mon Heur 4 · 2 0

Try using this:

void ShowDecimalRound( Decimal Argument, int Digits )
{
Decimal rounded = Decimal::Round( Argument, Digits );
Console::WriteLine ( dataFmt( rounded ) );
}

Then use:

ShowDecimalRound( Decimal::Parse( S"1.54" ), 1 );
ShowDecimalRound( Decimal::Parse( S"1.55" ), 1 );
ShowDecimalRound( Decimal::Parse( S"1.3456" ), 2);

The output for the above will be:

1.5
1.6
1.35

2007-04-10 03:13:04 · answer #2 · answered by Richard S 1 · 0 0

its no longer too stressful, you will would desire to comprise cmath for floor() and pow(): #comprise cmath #comprise iostream using namespace std; int considerable(){ flow value; // actual value to paintings with int dp; // decimal places cout << "enter actual quantity: "; cin >> value; cout << endl << "enter variety of decimal places: "; cin >> dp; flow ability = pow(10,dp); // for shifting the decimal factor up/down flow rounded = floor(value*ability+0.5)/ability; // make the rounded value cout << endl << "value after rounding: " << rounded; return 0; } that's fairly useful to function blunders coping with to that code to verify that valid values are examine from stdin yet different than which you have a working rounding software

2016-12-15 21:17:49 · answer #3 · answered by ? 4 · 0 0

Try this link. It seems to be all done for you.

2007-04-10 03:01:18 · answer #4 · answered by AnalProgrammer 7 · 0 0

fedest.com, questions and answers