So I watched a video on Pi's infinite series, given that today is Pi day (here in the US).
Trying to make some sort of ridiculous program that badly estimates Pi.
Here is my code:
//Pi estimator, to be safe only allow 20 didgets
#include <iostream>
usingnamespace std;
#define one = 1;
double estimator(int dg) {
int dgtimes2 = dg*2;
double piDiv = 1.0;
bool add = false;
int i = 3;
for (i;i<dgtimes2;i+=2) {
double oneOverI = 1/(i);
if (!add) {
piDiv -= oneOverI;
add = true;
} elseif (add) {
piDiv += oneOverI;
add = false;
} else {
cout << "Sorry, error" << endl;
return 0.0;
}
}
double piE = piDiv*4;
return piE;
}
void main() {
cout << "Welcome to the Pi estimator." << endl;
int dgts;
cout << "Please enter how accurate you want Pi to be: "; cin >> dgts;
cout << "Your Pi estimation is: " << estimator(dgts) << endl;
system("PAUSE");
}
Most of the COUT's in the estimator function are for debugging, because every time I run this, i enter around 5 for dgts, but it always returns 4. this is because the program never does the calculation 1/i correctly. Why is this not happening?
(The process is called the Gregory–Leibniz series)
... I've also tried entering up to 300 but it still returns 4.
Division of two integers results in another integer, so 1/i is always zero. 1.0/i is the correct way to do it.
Also, line 4 is nonsense, main() must return int, it is not necessary to "mention" i in the first part of the for loop, the if in line 16 is redundant and the final else block will never be executed.
Your starting the loop at 3 and counting by 2 while less then 10. 3 5 7 9
edit: that doesn't account for the 300 though.
Edit2: I completely misunderstood your issue.