Reputation: 291
I'm only a beginner, I've made a very simple program on SharpDevelop (C#), but it doesn't work.
Here it is:
public static void Main(string[] args)
{
float pi;
int n;
pi=1;
for(n=1; n<1000; n++)
{
pi=pi+((-1)^n)/(2*n+1);
Console.WriteLine(""+pi);
}
Console.ReadKey(true);
}
It should just calculate pi, but it only returns a lot of 1s instead... SharpDevelop doesn't report any "error".
Could somebody point out what errors I made?
Upvotes: 1
Views: 66
Reputation: 14059
It's because you are using an integer arithmetic, so each time your expression ((-1)^n)/(2*n+1)
is rounded to 0
.
Try to replace your pi
calculation with the following line:
pi += (float)Math.Pow(-1f, n) / (2*n+1);
By the way, the ^
operator is not the exponentiation.
Upvotes: 5