I cannot understand why it's truncating decimal

Greetings, this is my first post here, and I'm very new to C++ (and programming in general).

I'm coding a program to calculate a CD investment and display the CD worth month by month. Seems like standard fare for an introductory C++ course.

I have the logic and math working properly, but I can't understand why my output is dropping 1 decimal place. In other words, 10047.91 is being output as 10047.9. I believe I'm using the proper data types (double).

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
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	double cash, perc, months, month;
	
	cout << "Enter the initial cash value" << endl;
	cin >> cash;
	cout << endl;
	cout << "Enter the percentage yield" << endl;
	cin >> perc;
	cout << endl;
	cout << "Enter the number of months" << endl;
	cin >> months;
	cout << endl;
	cout << "Calculating..." << endl;
	for (month = 1; month <= months; month++)
	{
	cash = cash + (cash * perc / 1200);
	cout << month << " " << cash << endl;
	}
	system("PAUSE");
	return 0;
}


I removed my psuedocode and comments because this seems fairly straightforward. I'm sure this is a newbie mistake that I'm just not able to see...

Thanks in advance!

**Edit**

So I dug around a little more and found that I can use setprecision to force 2 decimals to be displayed. This seems like a bandaid, though, because once the numbers get sufficiently large, the output will be incorrect again. Plus, my teacher seems to frown upon rounding.

I must be missing something extremely simple...
Last edited on
http://www.codeguru.com/forum/archive/index.php/t-295798.html

http://www.arachnoid.com/cpptutor/student3.html

take a look at these links to be able to set presicion of the output.

hope this helps
It's not truncating/rounding, it's simply not displaying the decimals. Any calculations you do with the numbers will still be correct and precise.

A few tips for "cleaner code":
-Any "x = x +..." statement can be replaced by "x += ..."
-Any variable only used inside a for loop, can be defined inside the for loop:
1
2
for (int month = 1; month <= months; ++month) {
}

That way, you don't end up with variables that have no purpose.
-Avoid system() commands. They are, apparently, quite bad.
Yes, it helped very much! I used setiosflags(ios::fixed) << setprecision(2) to create the format that I want. I didn't worry about rounding because it seems that it's the default behavior.

Thank you for the links!
Topic archived. No new replies allowed.