我的代码有误吗?

时间:2018-07-31 12:25:47

标签: loops structure conditional-statements

我对编码非常陌生,我正在自己学习C。

我正在做我的第一个练习,我要创建一个概念为的“游戏”(“或多或少”):

-计算机选择一个介于1到100之间的随机数。

-我们得猜猜!

-找到神秘号码后游戏结束。

我放了一个功能循环(do..while)和一个功能(if ... else)来使游戏继续进行,即使您没有找到神秘号码(除非找到!)

几天以来,我一直受代码原因困扰,当我调试时,什么也没发生(所以这是一个很好的消息)但是,当我也运行没有发生< / strong>

我的代码是:

int main( int argc, char*argv[])

{

    int numberYouChoose = 0;
    int MysteryNumber = 0;
    const int MAX = 100, MIN = 1;


    printf("What's the number?\n");
    scanf("%d", &numberYouChoose);

 srand(time(NULL));
MysteryNumber = (rand() % (MAX - MIN + 1)) + MIN;


do{

    printf("Boooooh Try again!");
}while(numberYouChoose != MysteryNumber);

if (numberYouChoose == MysteryNumber);
 printf("Yay you found it!\n");


    return 0;
}

2 个答案:

答案 0 :(得分:0)

像一台计算机一样,一步一步走...您只问一个数字,而您再也不会问它了,所以它将永远停留在您的工作中。您需要在用户每次失败时询问。将您的Do-while更改为简单的while

while (numberYouChoose != MysteryNumber) {
    printf("Boooooh Try again!\n");
    printf("What's the number?\n");
    scanf_s("%d", &numberYouChoose);
}

printf("Yay you found it!\n");

编辑:

 if (numberYouChoose == MysteryNumber);
  {
    printf("Yay you found it!\n");
  }

这是多余的,当用户键入正确的数字时,您将退出while

这将是完整的代码:

int main(int argc, char*argv[])
{

    int numberYouChoose = 0;
    int MysteryNumber = 0;
    const int MAX = 100, MIN = 1;


    printf("What's the number?\n");
    scanf("%d", &numberYouChoose);

    srand(time(NULL));
    MysteryNumber = (rand() % (MAX - MIN + 1)) + MIN;


    while (numberYouChoose != MysteryNumber)
    {
        printf("Boooooh Try again!\n");
        printf("What's the number?\n");
        scanf_s("%d", &numberYouChoose);
    }

    printf("Yay you found it!\n");


    return 0;
}

答案 1 :(得分:0)

您的代码存在一些问题:

  1. Juan在先前的回答中指出,控制结构是错误的。简单地将do-while更改为while-do,即可在用户甚至没有机会进行猜测之前就将代码报告“ Boooh ...”(除非您重复要求输入数字,这不是一个好主意)。
  2. 在您的代码行if (numberYouChoose == MysteryNumber);中,结尾的;是一个空语句,因此后面的printf行将始终被执行。

以下作品:

int main( int argc, char*argv[])
{
    int numberYouChoose = 0;
    int MysteryNumber = 0;
    const int MAX = 100, MIN = 1;

    srand(time(NULL));

    MysteryNumber = (rand() % (MAX - MIN + 1)) + MIN;

    while ( 1 )
    {
        printf("What's the number?\n");
        scanf("%d", &numberYouChoose);
        if (numberYouChoose == MysteryNumber)
        {
            printf("Yay you found it!\n");
            break;
        }
        printf("Boooooh Try again!");
    }

     return 0;
}

( 1 )始终为true,因此,从理论上讲,这将永远循环。但是,如果您猜对了,代码将报告此情况,然后break会导致while循环终止,并且代码在while循环之后继续。