[英]Simple random numbers game program
這是我的代碼,這是一個簡單的數字游戲,用戶嘗試猜測隨機數,但是我無法弄清楚為什么您永遠不會贏。.我有兩件事無法解決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;
}
一個明確的問題是格式說明符不正確:
scanf("&d",&num1);
應該:
scanf("%d",&num1);
此外, while
循環中的最后2個條件將永遠不會被評估,因為如果猜測等於隨機數,則它不會進入循環。 可以使用do-while
循環來無限循環,並根據用戶輸入break
它。 記住要在循環中接受用戶輸入以進行猜測。
有很多缺陷,這是您要查找的代碼:
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到達數字后就停止了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.