Code rounding error

I have a school assignment that I am having a small issue with. Below is my code:

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
33
34
35
36
37
38
39
40
// This program calculates the amount paid for stock, the amount paid on commission, the total amount paid, and the amount she would need to pay to make a profit on the stock
#include <iostream>
using namespace std;

int main ()
{
	float stock; 
	float amountPaid;
	float commission;
	float AmountPaid;
	float makeProfit;
	float share;
	float totalAmountPaid;

	stock = 600.00;
	share = 21.77;	
	commission = 0.02;

	// Total amount paid for stock
	AmountPaid = stock * share;
	cout << "The amount you paid for the stock is $" << AmountPaid << endl;

	// Total amount paid on commission
	commission = AmountPaid * commission;
	cout << "The total amount you paid on commission is $" << commission << endl;

	// Total amount paid for stock plus commission 
	totalAmountPaid = AmountPaid + commission; 
	cout << "The total amount you paid for the stock including commission is $" << totalAmountPaid << endl;
	
	// The minimal amount needed to sell the stocks to make a profit
	makeProfit = totalAmountPaid / stock; 
	cout << "The amount needed to sell the stock in order to make a profit is $" << makeProfit << endl;


cin.ignore().get();
return 0;

}


The output is correct, EXCEPT for the totalAmountPaid variable. It displays 13323.2 instead of the correct 13323.24. I've tried changing from float to double to int for every variable, but I cannot for the life of me figure out why this number is rounding incorrectly. Both the makeProfit and commission variable display their decimals rounded correctly. Any help would be greatly appreciated.
Last edited on
try to use setprecision() function
Thank you, this worked. I'm still not sure why though... Can you explain why it needed to be set for this variable and not the others?
Whe you take a float (say 13.999) and then convert it into a int then the values will be lost (this will be clear when you read about binary and one's complement and two's complement) so the value of float which is now int will be sometimes undesired (here 13 although we would assume it to be 14)...

For further information~
http://www.cplusplus.com/reference/iomanip/setprecision/

Last edited on
Topic archived. No new replies allowed.