【发布时间】: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