【问题标题】:Square root of consecutive integers连续整数的平方根
【发布时间】:2026-02-09 12:30:01
【问题描述】:

为什么我会收到错误的答案?这是我的代码:

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-4 写成 i -= 4
  • 你的代码只是计算 sqrt(n) + sqrt(n) + ..; + sqrt(n) + 1
  • 要获得正确答案,您需要从 13 的平方根开始倒推(秒示例 17)。
  • @EtienneCharland 是的,我知道,但是当我执行程序时,它给了我错误的答案;我正在尽一切努力纠正这一点。谢谢顺便说一句
  • @AnotherProgrammer 是的,我在学习thanx时没有意识到这一点!

标签: c# math square-root


【解决方案1】:

对于每个整数i,平方根应该应用于到现在的总和,而不仅仅是当前的i

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

【讨论】:

    【解决方案2】:

    这里的问题是您每次都添加n 的平方根。 n 的值是在循环之前分配的,并且永远不会更改。您每次都需要增加i + total 的平方根,而不是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();
    

    请随意查看pre and post increment/decrement 之间的区别。

    int i = 1;
    int x = i++; //x is 1, i is 2
    int y = ++i; //y is 3, i is 3
    

    【讨论】:

    • 我认为你的答案也是错误的@Mureinik 确实正确,但你是对的我忘记在 for 循环中输入 i,我只是编码为 'n' 并且它是如此错误:) 谢谢你我意识到我的更多错误之一。