0

我想要做的是使用for循环,计算根下的根之和(不是数学家,不知道你怎么称呼它)。

顺序应该是这样的:

Sqrt(2 + Sqrt(2 + ... + Sqrt(2))), where n > 0.

例如,如果n = 3for循环上(while i = 1, i++),它应该使这个算术序列:

sum += Math.Sqrt(2 + Math.Sqrt(2 + Math.Sqrt(2)));

如果 n = 4:

sum += Math.Sqrt(2 + Math.Sqrt(2 + Math.Sqrt(2 + Math.Sqrt(2))));

所以问题是我不知道如何n通过在根下添加根直到循环结束来循环槽。

我的代码模板

        public static double GetSumOfRoots(int n)
        {
            double sum = 0;
            for (int i = 1; i <= n; i++)
            {
                sum += ...;
            }

            return sum;
        }

如果我的描述不清楚,请告诉我,我会尽力而为,谢谢。

4

2 回答 2

3

打开循环,看看发生了什么:

  n : formula
  -------------------------------------------------------
  0 : 0                           = 0    
  1 : Sqrt(2)                     = Sqrt(2 + item(0))
  2 : Sqrt(2 + Sqrt(2))           = Sqrt(2 + item(1)) 
  3 : Sqrt(2 + Sqrt(2 + Sqrt(2))) = Sqrt(2 + item(2))
  ....
  n : Sqrt(2 + ...)               = Sqrt(2 + item(n - 1))
  ....

完成数学运算后,您可以编写相应的代码:

    public static double GetSumOfRoots(int n)
    {
        if (n < 0)
            throw new ArgumentOutOfRangeException(nameof(n)); 

        double sum = 0;
    
        for (int i = 1; i <= n; i++)
        {
            // Note assignment = instead of +=
            sum = Math.Sqrt(2 + sum);
        }

        return sum;
    }

您可以在Linq的帮助下简化例程:

    using System.Linq;

    ...

    public static double GetSumOfRoots(int n)
    {
        if (n < 0)
            throw new ArgumentOutOfRangeException(nameof(n)); 

        return Enumerable
          .Range(0, n)
          .Aggregate(0.0, (s, a) => Math.Sqrt(2 + s));
    }

演示:

  var report = string.Join(Environment.NewLine, Enumerable
    .Range(0, 10)
    .Select(n => $"{n} : {GetSumOfRoots(n)}"));

  Console.Write(report);

结果:

0 : 0
1 : 1.4142135623730951
2 : 1.8477590650225735
3 : 1.9615705608064609
4 : 1.9903694533443939
5 : 1.9975909124103448
6 : 1.9993976373924085
7 : 1.999849403678289
8 : 1.9999623505652022
9 : 1.9999905876191524
于 2021-08-09T18:40:48.750 回答
0

我相信最好的解决方案是递归:

 public static double GetSumOfRoots(int n)
    {
        double sum = 0;
        sum = calculate(n);
        return sum;
    }
    public static double calculate(int n)
    {
        if(n == 0)
            return Math.Sqrt(2);

        return Math.Sqrt(2 + calculate(n-1));
    }
于 2021-08-09T18:42:16.723 回答