【问题标题】:Why doesn't the if statement print 'well done' and why does the loop repeat out questions()为什么 if 语句不打印“做得好”,为什么循环会重复 questions()
【发布时间】:2019-12-23 17:03:46
【问题描述】:

我想制作一个游戏,让你在电脑上轮流三圈猜出选定的数字。然而,即使你得到了正确的数字(已经使用 printf 语句测试过),它也永远不会说做得好,并且循环也会因为继续或运行两次而搞砸。

我已尝试删除中断。 我已经放入了 printf 语句来检查 randomise 和 questions 是否真的存储了正确的值并且它们确实存在。

# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# include <time.h>

int questions() {

    int num;

    printf("Chose a number between one - ten: ");
    scanf("%d",&num);

    return num;

}

int randomise() {

    int roll;

    srand(time(NULL));

    roll = rand()%10 + 1;
    return roll;

}

int main() {

    int chosenNum, enteredNum, i;

    chosenNum = randomise();
    enteredNum = questions();

    for(i = 0; i < 10; i++) {
        if(chosenNum != enteredNum) {

            questions();
            break;

        }
        else if(chosenNum == enteredNum) {

            printf("WELL DONE !!!");

        }
    }

    return 0;
}

零错误和零警告。结果应该是你做得很好。

【问题讨论】:

  • 文字不能太短,但可以尝试在邮件末尾添加"\n""WELL DONE !!!\n"
  • chosenNum = questions();break 在错误的分支...
  • 注意srand() — why call it only once?。这不是您的问题,因为您只调用一次randomise()。但这是您需要尽快注意的事情。您的“做得好”消息应以换行符结尾。
  • 感谢您的 cmets,我已使用您的所有反馈,并将尽快发布代码。谢谢

标签: c loops if-statement random


【解决方案1】:

有两个问题:

  1. 您正在使用break,如果第一个数字不匹配,则不允许再次尝试输入该数字,并且
  2. 循环中questions()的返回值没有分配给enteredNum(这意味着它将第二次尝试旧号码)。

【讨论】:

  • 感谢您的反馈,我已经接受了它,现在它可以完美运行了。干杯
【解决方案2】:

enteredNum 永远不会设置在循环内。因此,除非第一次为假,否则 if 不可能为假。

把你的循环改成这样:

for(i = 0; i < 10; i++){
 if(chosenNum != enteredNum){

    enteredNum = questions();
    break;

   }
   else if(chosenNum == enteredNum){

      printf("WELL DONE !!!");

   }
}

【讨论】:

  • 但是break 是不想要的。
【解决方案3】:

这是代码的最新更新,感谢大家的帮助。反馈很棒!代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int questions(){

int num;

printf("Chose a number between one - ten: ");
scanf("%d",&num);

return num;

}

int randomise() {

int roll;

srand(time(NULL));

roll = rand()%10 + 1;

return roll;

}

int main(){

int chosenNum, enteredNum, i;

int life = 3;

chosenNum = randomise();
enteredNum = questions();

for(i = 0; i < 2; i++){

enteredNum = questions();

 if((enteredNum != chosenNum) && life > 0){

    life -= 1;

    if(life == 1 ){

    printf("GAME OVER !!!\n");
    break;

      }

    }
    else if((chosenNum == enteredNum) && life > 0){

    printf("WELL DONE !!!\n");
    break;

   }

}

return 0;

}

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多