Numbers Drifting

Hi Guys
Heres My Code It's really Simple I'm very very new so hope you all can help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "stdafx.h"
#include <iostream>

int main()
{
    using namespace std;
	cout << "Welcome To Joels Bakehouse" << endl;
	cout << "White Loaves are $3.20 Each" << endl;
    cout << "How many loaves of bread would you like:" << endl;
	int nWhiteLoavesAmount;
	cin >> nWhiteLoavesAmount;
	float fMoney = 3.20;
	float fMoney2 = fMoney*nWhiteLoavesAmount;
	int nDollars =fMoney2;
	int nCents =(fMoney2-nDollars)*100;	
	cout << "That comes to: " << nDollars << " Dollars and " << nCents << " Cents" << endl;
	bool Eftpos;
	cout << "To Pay By Cash Type 0" << endl;
	cout << "To Pay By Eftpos Type 1" << endl;
	cin >> Eftpos;
if (Eftpos)
	cout << ".... Transaction Confirmed. Thank you for your buisness!" << endl;
else
{
	cout << "Okay, How Much Cash Do You Have?" << endl;
	float Cash;
	cin >> Cash;
	cout << "Thats" << Cash-fMoney2 << " Change" << endl;
	cout << "Thank you for your buisness!" << endl;
}
	return 0;
}

The Problem is if you ask for say
7 loaves of bread you end up with $22 and 39 Cents not 40 Cents ???
I Think Ive read about this but i cant work it out

Thanks for your help
Joel:)
I would suspect floating point approximation errors here. Why not just store all monetary values as integers representing the number of cents?
Floating point numbers cannot represent every decimal exactly (in fact, there are infinitely many more that it cannot represent than it can represent).

http://floating-point-gui.de/

Don't use float for money (or anything where you need exact calculations). Commonly, people use integers values for money.
Okay Used Double instead of float fixed it completly

Thanks All
Joel
Last edited on
A double IS a floating point number. A double may have more precision than a regular float (the standard doesn't dictate that it will). Don't use floating point numbers when dealing with money. Use int.
Topic archived. No new replies allowed.