【问题标题】:Simple random numbers game program简单的随机数游戏程序
【发布时间】:2014-02-10 03:27:22
【问题描述】:

这是我的代码,这是一个简单的数字游戏,用户试图猜测随机数,但是我不知道为什么你永远不会赢。有两件事我无法解决 1) 用户永远猜不出正确的数字 2) 我想猜猜 3 次,尽管我似乎无法抓住我忽略的内容

// C_program_random_number_game

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




int main(){

srand(time(NULL));
int num1,x;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y'){

    printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
    do{
    int r = rand()%25 +1;
    printf("\n\nEnter a number between 1 and 5 : ");
    scanf("%d",&num1);
    do{
    for(x=1; x<=3; x++){

    if(num1 < r){
        printf("\nClose! try a little higher... : ");
    }
    else if (num1 > r){
        printf("\nClose! try a little lower...: ");
    }
    scanf("%d",&num1);
    }
    }while(num1!=r || x <= 3);
    printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
    printf("\nWould you like to play again? (y or n) : ");
    scanf("\n%c",&replay);
    }while(replay == 'y'|| replay == 'Y');
}
    printf("Thanks for playing! ");

    if (game == 'n' || game == 'N'){
    printf("Okay, maybe next time! ");
    }
    return 0;
}

【问题讨论】:

  • 你把(num1 == r)放在(num1 != r)....
  • 我很困惑...我要切换它们吗?
  • 好吧,这没有任何意义,因为 while 循环确保 num1 != r 然后在你内部检查它是否相等......因此永远不会是真的
  • 您可能应该使用while (true),然后在分支else if(num1 == r){ } 中添加break 语句以退出循环。此外,如果你给出一个简短的输入/输出序列,这将有助于诊断。
  • 谢谢你!巨大的帮助!看到这个小代码,我的眼睛都疼了哈哈……再次感谢!

标签: c if-statement while-loop srand


【解决方案1】:

一个明确的问题是格式说明符不正确:

scanf("&d",&num1);

应该是:

scanf("%d",&num1);

此外,您的while 循环中的最后两个条件永远不会被评估,因为如果猜测等于随机数,它就不会进入循环。使用do-while 循环代替无限 循环,并根据用户输入将break 循环出来。请记住在循环中获取用户输入的猜测

【讨论】:

  • 感谢您的帮助!我将其更改为 do while 虽然在判断 HIGH 或 LOW 条件之后似乎仍未达到它...知道为什么吗?
  • @Djeter277 使用无限循环,即do {} while(1);break 根据您的需要退出。
  • @Djeter277 我知道为什么,正如我在回答中解释的那样
【解决方案2】:

有各种缺陷,这里是你要找的代码:

while(num1 != r){
    if(num1 < r){
        printf("higher... : ");
    }
    else{
        printf("lower...: ");
    }
    scanf("%d",&num1);
}
printf("Winner! >> you entered %d and the computer generated %d! \n",num1, r);
printf("Would you like to play again? (y or n) : ");
scanf("%c",&replay);

正如我在上面的评论中指出的,之前在 while 循环中,永远不会有 num1==r 的时候,因此里面的 if 语句永远不会是真的。现在,循环 jsut 在到达数字后就停止了。

【讨论】:

  • 嘿,非常感谢!会看一整夜哈哈..谢谢你!
  • 如果它是您选择的正确答案,请单击答案旁边的检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
相关资源
最近更新 更多