Reputation: 25
sorry if this is quite a simple question, I am just currently in the process of teaching myself C#.
foreach(int n in Enumerable.Range(0, Range)) {
double s += (1 / Math.Pow(n, 2));
double s6 = s * 6;
double pi = Math.Sqrt(s6);
Console.WriteLine("Pi is equal to {0}", pi);
}
This returns the error "invalid expression term '+='".
I previously wrote a program in python which performs the same task however, I want the line;
double s = (1 / Math.Pow(n, 2));
to add to itself while the foreach loop is true, in a similar fashion to my python variation;
s += 1/n**2;
Thanks in advance for any help!
Upvotes: 0
Views: 65
Reputation: 467
As mentioned in the comments, there is a scope issue. s must be declared outside the loop and set an initial value to use += in the intended way.
double s = 0;
foreach(int n in Enumerable.Range(0, Range))
{
s += (1 / Math.Pow(n, 2));
double s6 = s * 6;
double pi = Math.Sqrt(s6);
Console.WriteLine("Pi is equal to {0}", pi);
}
Upvotes: 3
Reputation: 2320
Just need to initialize it first.
double s = 0;
foreach(int n in Enumerable.Range(0, Range)) {
s += (1 / Math.Pow(n, 2));
double s6 = s * 6;
double pi = Math.Sqrt(s6);
Console.WriteLine("Pi is equal to {0}", pi);
}
Upvotes: 1