是否可以通过if语句打印步骤总数?

时间:2019-10-04 12:05:18

标签: c if-statement towers-of-hanoi

我正在为C入门课程中的作业问题为河内塔写一些代码。我已经运行了实际的程序,但作为附录,我希望代码打印出已执行的步骤数,即“步骤总数为31”。然后,我想将它们与理论上的步骤数进行比较(例如steps = (2^n)-1,其中n是磁盘数),并能够验证程序对于较大的n是否正确运行。

到目前为止,我已经能够实现代码以打印出所需的预期步骤数,但是我不确定如何继续进行控制台以打印实际步骤数。

void towers(int, char, char, char);
int main()
{
    int n;
    printf("Number of disks:");
    scanf("%d", &n);
    int result = (pow(2,n)-1);
    printf("\nExpected number of moves required is %d", result);
    towers(n, 'A', 'C', 'B'); //moving n disks from A to C using B as the intermediate
    return 0;
}

result在运行Towers函数之前,从power函数调用并返回预期的步数。

void towers(int n, char from_peg, char to_peg, char other_peg)
{
    if (n == 1) //breaking condition
    {
        printf("\n Move disk 1 from peg %c to peg %c", from_peg, to_peg);
        return;
    }
    towers(n-1, from_peg, other_peg, to_peg); //moving n-1 disks from A to B using C as the intermediate
    printf("\n Move disk %d from peg %c to peg %c", n, from_peg, to_peg);
    towers(n-1,other_peg,to_peg,from_peg); //moving n-1 disks from B to C using A as the intermediate
}

循环每次将解决方案返回给塔拼图打印动作。

理想情况下,我希望在循环完全声明“所需的移动总数为(步数)”之后运行一些代码,然后将预期结果与实际结果进行比较(即expected step number == actual step number为是的)。

2 个答案:

答案 0 :(得分:1)

您有一些选择。最简单的方法是声明一个全局变量,将其初始化为零,然后在每个步骤将其递增。然后,您只需打印它即可。

如果要避免使用全局变量,这通常是一件好事,则可以通过指针传递变量。像这样:

@Push

避免全局变量的另一种方法是使用静态方法。

void towers(int n, char from_peg, char to_peg, char other_peg, int * no_steps)
{
    (*no_steps)++;
    ...

答案 1 :(得分:1)

一种方法是让towers()返回已采取的步骤数:

int towers(int n, char from_peg, char to_peg, char other_peg)
{
    int steps = 0;

    if (n > 0)
    {
        steps += towers(n-1, from_peg, other_peg, to_peg); //moving n-1 disks from A to B using C as the intermediate
        steps += 1;
        printf("\n Move disk %d from peg %c to peg %c", n, from_peg, to_peg);
        steps += towers(n-1,other_peg,to_peg,from_peg); //moving n-1 disks from B to C using A as the intermediate
    }
    return steps;
}

用法:

int actual = towers(n, 'A', 'C', 'B');
printf("\nActual number of moves used is %d", actual);

(我一直都习惯于将\n放在打印输出的开头,但是在结尾处比较传统!)