解决此递归的最佳方法是什么?
我自己学习,遇到了以下问题,我不知道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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基于以下公式( source ),您可以将代码重写为计算:
注意:α表示
n
,β表示m
。可以用代码表示:
Based on the following formula (source), you can rewrite your code as a calculation:
Note: α represents
n
and β representsm
.Which can be expressed in code as: