C# 连续整数的平方根

C# 连续整数的平方根,c#,math,square-root,C#,Math,Square Root,为什么我会收到不正确的答案?这是我的代码: Console.WriteLine("Please input a number for the formula: i.e. (1,5,9,13...)"); int n = Convert.ToInt32(Console.ReadLine()); double total = 0; for (int i = n; i >=1; i=i-4) { if (i == 1) total++; else

为什么我会收到不正确的答案?这是我的代码:

Console.WriteLine("Please input a number for the formula: i.e. (1,5,9,13...)");
int n = Convert.ToInt32(Console.ReadLine());
double total = 0;
for (int i = n; i >=1; i=i-4)
{
    if (i == 1)
        total++;
    else
        total += Math.Sqrt(n);
}

Console.Write(total);

对于每个整数
i
,应将平方根应用于到目前为止的总和,而不仅仅是当前的
i

double total = 0;
for (int i = n; i >= 1; i-=4)
{
     total = Math.Sqrt(total + i);
}

这里的问题是每次都要加上
n
的平方根。
n
的值是在循环之前分配的,永远不会更改。您每次需要增加
i+总计的平方根,而不是
n
的平方根:

// My input for testing was 13.
int n = int.Parse(Console.ReadLine());
double total = 0;
for (int i = n; i > 1; i -=4)
    total = Math.Sqrt(total + i);

Console.WriteLine($"Total: {Math.Sqrt(++total)} = 1.980.");
Console.ReadKey();
请随便看看两者之间的区别


顺便说一句,你可以把i=i-4写成i-=4你的代码只是在计算sqrt(n)+sqrt(n)+;+sqrt(n)+1要得到正确的答案,你需要从13秒的平方根开始反向工作(例17)。@EtienneCharland是的,我知道,但当我兴奋的时候,程序给了我错误的答案;我正在尽一切努力纠正这一点。塔克斯btw@AnotherProgrammer是的,我在学习thanx的时候没有意识到这一点!我认为你的答案也错了@Mureinik确实正确,但你是对的我忘了在for循环中输入I,我只是将“n”编码为as,这是非常错误的:)Thanx对你说,我意识到我还有一个错误。
int i = 1;
int x = i++; //x is 1, i is 2
int y = ++i; //y is 3, i is 3