user87073 user87073 - 5 days ago 9
C# Question

c# change equation every loop run


I'm creating a pi calculator but i bumped into a problem, this is the code:

for (;;) {
pi = (4*(1/5 /*here would go - or + */ (1/(n * Pow(5, n))) ) ) - n;
n++;

System.Diagnostics.Debug.WriteLine("Result: " + pi);
System.Diagnostics.Debug.WriteLine("Loop runs: " + loopRuns);
loopRuns += 1;
if (n == iterations)
{
Done(0);
break;
}
}


i need a way to make t so that every run of the loop, it varies - and +

any help appreciated.

Answer

The simplest way to do this is to have a variable outside the loop:

int modifier = 1; // Or -1, depending on how you want to start

Then inside the loop:

pi = (4*(1/5 + (1/(n * Pow(5, n))) * modifier ) ) - n;
modifier *= -1;