Float Number Multiplied by 100 to Turn Into Integer

I need to write a program that converts an input of money in the format of dollars and cents (2.53) and output it into how many quarters, nickles, dimes, pennies that is.

I'm stuck here at this part, when I multiply the input by 100 to turn it into an integer so I can divide by modulus, sometimes the multiplied by number will be one off.

Here's my code:

#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

float amt;
int morph, temp, dtemp, ntemp, ptemp,
quar, nick, dimes, pen;


cout << "Please enter an amount in dollars and cents: ";
cin >> amt;

morph = amt * 100; //turn input into an integer


//Output formatting

cout << setiosflags (ios::fixed)
<< setiosflags (ios::showpoint);
<< setw(5)
<< setprecision(2);

//Output formatting

cout << setw(2) << amt << " is the amount to be converted\n";
cout << setprecision(2) << morph << "<----- amount after conversion to int" << endl;

system ("pause");
return 0;

}


Enter the amount of 2.53 to see what I mean, 2.53 should be 253 after multiplying by 100, but instead, they give me 252.

Any help on fixing this? Thanks
Try using double, not float as your floating point type. Floating point variables are only 32bit, whereas double should be 64bit, and thus have a greater precision.

(Unless, of course, this is an assignment and your lecturer specified that you must use float...)
Last edited on
My professor said that I can use double also but after trying it, it yields the same results
Anyone? This doesn't make any sense, if I multiply anything by 100, it should yield it to be even, I don't see why some amounts I'm typing in, they're giving me an integer but -1
Read the input as two integers, dollars and cents
I can't. The professor said the input has to be float.

What I ended up doing was because of the truncation, I did:

morph = (amt * 100) + 0.5

Now everything, is accurate.
Topic archived. No new replies allowed.