l made a script to calculate pi, and it worked just fine, but I tried to make it less messy with a for loop, but then it broke and started giving weird, seemingly random outputs like -2.468526e+142, stuff like that (not an actual example)
So I'm pretty sure it has something to do with the for loop. Could someone take a look?
//This calculation uses the equation:
//(1 * -1/3 * 1/5 * -1/7...) * 4
#include <iostream>
usingnamespace std;
int main() {
double n = 1;
double bank = 0;
double d = 1;
double f;
double pi;
int i;
for (int i = 1000000; i = 0; i--){
f = 1/i;
bank = bank + f * d;
d = d * -1;
n = n + 2;
pi = bank * 4;
}
if (i <= 0){
cout<<"Pi is aproximately "<<pi<<"!";
}
return 0;
}
Your loop never executes because of your test condition (i = 0). Even if your test condition were syntactically correct (i == 0) the for loop would never execute.
You never assign a starting value to pi when you create it. Because your loop never executes you print out whatever garbage value was in the memory location assigned to pi.
One side note: are you sure you want your loop variable to ever be 0? Dividing by zero is BAD NEWS!
#include <iostream>
int main()
{
double n = 1;
double bank = 0.0;
double d = 1;
double f;
double pi = 0.0;
// int i;
for (int i = 1000000; i > 0; i--)
{
f = 1.0/i;
bank = bank + f * d;
d = d * -1;
n = n + 2;
pi = bank * 4;
}
std::cout << "Pi is approximately " << pi <<"!\n";
}
Pi is approximately -2.77259!
Well, we now have output because the loop is executed, but we still get a very wrong result.
Something in how you calculate PI in your loop is mathematically flawed.
A for loop test condition (VERY simplified) acts as an if statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
int main()
{
int i = 100000;
if (i == 0)
{
// do something!!
std::cout << "I'm doing something!\n";
}
std::cout << "Did I just do something?\n";
}
#include <iostream>
usingnamespace std;
int main() {
double s, f, pi;
double d = 1;
double x = 1;
for (int i = 0; i < 1000000; i++){
f = 1/d;
s += f * x;
x *= -1;
d += 2;
pi = s * 4;
}
cout<<"Pi is ~"<<pi;
return 0;
}
//This calculation uses the equation:
//(1 * -1/3 * 1/5 * -1/7...) * 4
#include <iostream>
usingnamespace std;
int main() {
double s = 0, f = 0, pi = 0;
double d = 1, x = 1;
for (int i = 0; i < 1000000; i++){
f = 1/d;
s += f * x;
x *= -1;
d += 2;
pi = s * 4;
}
cout<<"Pi is ~"<<pi;
return 0;
}
//This calculation uses the equation:
//(1 * -1/3 * 1/5 * -1/7...) * 4
Don't end your loop at a fixed number (1000000). You should exit the loop when the new term (f*x) is so small that it makes no significant change to answer.