解决此递归的最佳方法是什么?

发布于 2025-01-22 16:35:36 字数 828 浏览 0 评论 0原文

我自己学习,遇到了以下问题,我不知道C#(我来自JavaScript)。有关我的猜测,请参见下文,欢迎任何额外的解释/澄清/更正。

以下代码会做什么,如何改进代码(给定n = 1和m = 10)?

class Program
{  public static int DoSomething(int n, int m)
   {
      int x = n;

      if (n < m)
      {
        n++;
        return x += DoSomething(n, m);
      }
      return x;
   }

   static void Main(string[] args)
   {
     Console.WriteLine("Enter n: ");
     int n = Convert.ToInt32(Console.ReadLine());

     Console.WriteLine("Enter m: ");
     int m = Convert.ToInt32(Console.ReadLine());

     int x = DoSomething(n, m) ;

     Console.WriteLine(x);

     Console.ReadKey();
   }
}

所以这显然是一个递归问题吗?看起来它会增加n直到大于m,然后将该数字写入控制台。因此,最终它将将11记录到控制台(我总共假设它将将1-11记录到控制台)。递归是多余的和不必要的,因此对我来说简单的解决方案就是将其转换为简单的循环,而n&lt; m,console.Writeline(N)和N ++。我是否缺少某些东西,还是在这种情况下这是最好的简单解决方案?

I'm studying on my own and came across the following problem, and I don't know much C# (I'm coming from JavaScript). See below for my guess and any extra explanation/clarification/correction is welcome.

What does the following code do and how would you improve the code (Given n=1 and m=10)?

class Program
{  public static int DoSomething(int n, int m)
   {
      int x = n;

      if (n < m)
      {
        n++;
        return x += DoSomething(n, m);
      }
      return x;
   }

   static void Main(string[] args)
   {
     Console.WriteLine("Enter n: ");
     int n = Convert.ToInt32(Console.ReadLine());

     Console.WriteLine("Enter m: ");
     int m = Convert.ToInt32(Console.ReadLine());

     int x = DoSomething(n, m) ;

     Console.WriteLine(x);

     Console.ReadKey();
   }
}

So it's obviously a recursion problem right? It looks like it will increment n until it is greater than m and then write that number to the console. So eventually it will log 11 to the console (I'm assuming in total, it will log 1-11 to the console). The recursion is redundant and unnecessary and so the easy solution to me would be to just convert it to a simple while loop, where as long as n < m, Console.WriteLine(n) and n++. Am I missing something, or is that the best simple solution in this scenario?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

佼人 2025-01-29 16:35:36

基于以下公式( source ),您可以将代码重写为计算:

注意:α表示n,β表示m

可以用代码表示:

public static int DoSomething(int n, int m)
{
    int numerator = (m - n + 1) * (n + m);
    int result = numerator / 2;
    return result;
}

Based on the following formula (source), you can rewrite your code as a calculation:

enter image description here

Note: α represents n and β represents m.

Which can be expressed in code as:

public static int DoSomething(int n, int m)
{
    int numerator = (m - n + 1) * (n + m);
    int result = numerator / 2;
    return result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文