简单的随机数游戏程序

时间:2014-02-10 03:27:22

标签: c if-statement while-loop srand

这是我的代码,这是一个简单的数字游戏,用户试图猜测随机数,然而,我无法弄清楚为什么你永远不会赢。有两件事我无法解决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;
}

2 个答案:

答案 0 :(得分:3)

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

scanf("&d",&num1);

应该是:

scanf("%d",&num1);

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

答案 1 :(得分:1)

存在各种缺陷,这是您要查找的代码:

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在达到数字后就会停止。