迭代流程问题

.Net技术 码拜 8年前 (2016-02-27) 711次浏览
正在自学C#,有一个问题弄不清楚,讨教一下。
一个汉诺塔求操作步数,输入层数,然后得到答案。本人试着写了一下,验证了一下发现结果都对。但是程序具体的计算流程还是搞不清楚,例如本人假如输入的层数是4的话,结果不应该是 1+6+4+2=13吗?求指导答。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
Calculator x = new Calculator();
Console.WriteLine(“Please input a number:”);
int num = Convert.ToInt32(Console.ReadLine());
Console.Write(“The answer is:”);
ulong answer = x.claVar(num);
Console.WriteLine(answer);
Console.ReadKey();
}
}
class Calculator
{
public ulong claVar(int a)
{
ulong result = 0;
if (a == 1)
{
result = 1;
}
else
{
result = 1+ 2*claVar(a-1);

}
return result;
}
}
}

解决方案

40

    class Calculator
    {
        public ulong claVar(int a)
        {
            Debug.Print("input:a={0}", a);
            ulong result = 0;
            if (a == 1)
            {
                result = 1;
            }
            else
            {
                result = 1 + 2 * claVar(a - 1);
            }
            Debug.Print("output:【a={0}, result={1}】", a, result);
            return result;
        }
    }

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明迭代流程问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)