给定x = 3;
我需要计算x = 3 + 2 + 1
x = 6;
int input = 3;
int retVal = 0;
for (int i = 0; i <= input; i++)
{
retVal += i;
}
Console.WriteLine(retVal);
我能够计算x的总和。
我如何计算x ^ 2总和的值
例如
x x^2
1 1
2 4
3 9
summation of x = 6
summation of x^2 = 14
我尝试过以下代码
int input = 3;
int retVal = 0;
int summation = input * input;
for (int i = 0; i <= input; i++)
{
retVal += i;
summation += i;
}
Console.WriteLine(retVal);
Console.WriteLine(summation);
答案 0 :(得分:4)
让我向您解释一下您的代码:
int input = 3;
int retVal = 0;
int summation = input * input; //summation is equal to 9
for (int i = 0; i <= input; i++)
{
retVal += i;
summation += i; /*this is basically saying add summation plus i
tosummation (9 is assigned 9 + 0 so summation is still 9). Then, when i is 1,
summation changes to 10. When i is 2, summation changes to 12, and when i is 3,
summation is 15. What you should be doing is initialize summation to 0 and in
the for loop, do this: summation += i * i (summation is assigned summation + (i * i)) Also, no need to start i from 0 (it is doing one extra loop for nothing). You should start i from 1. */
}
Console.WriteLine(retVal);
Console.WriteLine(summation); //Another user already provided the solution. I just wanted to explain you your code.
答案 1 :(得分:1)
您可以使用Enumerable.Range()
来实现此目的。
public static int Summation(int count, Func<int, int> series)
{
return Enumerable.Range(1, count).Select(series).Sum();
}
使用示例 - Summation(3, x => x * x)
将返回14
。