Display length of a double?

So I got my last program working, and when I calculate with a double my program only shows a Pi estimation to 6 digits.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double estimatorD(int dg) {
	int dgtimes2 = dg*2;
	double piE = 4.0;
	bool add = false;
	for (int i = 3;i<dgtimes2;i+=2) {
		double fourOverI = 4.0/i;
		if (!add) {
			piE -= fourOverI;
			add = true;
		} else {
			piE += fourOverI;
			add = false;
		}
	}
	return piE;
}

How would I increase the length of this calculation?
If you pass a larger value for dg the result will be more precise.

To print more decimals you can use std::setprecision
std::cout << std::setprecision(20) << estimatorD(5000);
Last edited on
that doesn't seem to be working.
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
41
42
43
44
45
#include <iostream>
using namespace std;

double estimatorD(int dg) {
	int dgtimes2 = dg*2;
	double piE = 4.0;
	bool add = false;
	for (int i = 3;i<dgtimes2;i+=2) {
		double fourOverI = 4.0/i;
		if (!add) {
			piE -= fourOverI;
			add = true;
		} else {
			piE += fourOverI;
			add = false;
		}
	}
	return piE;
}
float estimatorF(int dg) {
	int dgtimes2 = dg*2;
	float piE = 4.0;
	bool add = false;
	for (int i = 3;i<dgtimes2;i+=2) {
		float fourOverI = 4.0/i;
		if (!add) {
			piE -= fourOverI;
			add = true;
		} else {
			piE += fourOverI;
			add = false;
		}
	}
	return piE;
}
void main() {
	cout << "Welcome to the Pi estimator." << endl;
	int dgts;
	cout << "Please enter how many terms you want to calculate: "; cin >> dgts;
	int ford;
	cout << "Using FLOAT or DOUBLE? (f = 1/d = 2) "; cin >> ford;
	if (ford == 2) cout << "Your Pi estimation is: " << estimatorD(dgts) << endl;
	else cout << "Your Pi estimation is: "  << estimatorF(dgts) << endl;
	system("PAUSE");
}

Do i need to import something?
that doesn't seem to be working.


You don't seem to have actually used setprecision.
To use std::setposition you have to include <iomanip>.
You don't seem to have actually used setprecision.

Peter87 took care of this, I was trying to show you how my program was structured so you could see that I didn't have the correct import.
Do i need to import something?

I mean #include. same thing.
same thing.


It's not.
ok. I'm sorry. I'm better at java.
Topic archived. No new replies allowed.