English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

我的程式:
#include
#include
#include
int main()
{
srand(time(NULL));

int x,y;
char z;

y=1+rand()%1000;

printf("I have a number between 1 and 1000\n");
printf("Can you guess my number?\n");
printf("Please type your first guess:\n");
scanf("%d",&x);

while ( x <=1000 && x>=1 )
{ if ( x > y )
{printf("Too high. Try again.\n");
scanf("%d",&x);
continue;}
if ( x < y )
{printf("Too low. Try again.\n");
scanf("%d",&x);
continue;}
if ( x == y )
{ printf("Excellent!You guessed the number!\n");
printf("Would you like to play again( y or n )?\n");
scanf("%c",&z);
if ( z == 'y')
{ printf("I have a number between 1 and 1000\n");
printf("Can you guess my number?\n");
printf("Please type your guess:\n");
scanf("%d",&x);

y=1+rand()%1000;
continue;}
if ( z == 'n')
{ break; }
}
}

system("pause");
return 0;
}


當我猜對之後為什麼他會連印2次
Excellent!You guessed the number!
Would you like to play again( y or n )?

2007-11-01 16:13:31 · 1 個解答 · 發問者 Deep 3 in 電腦與網際網路 程式設計

1 個解答

#include
#include
#include
#include
#define randomize() srand((unsigned)time(NULL))
int main(int argc, char* argv[]){
//=====START=====//
int x,y;
char str[2]="y";
randomize();
do{
y=(strcmp(str,"a")?rand()%1000+1:y);
printf("Input a number between 1 and 1000: "),scanf("%d",&x);
printf("%s\n",(x!=y?(x>y?"Too Big.":"Too Small."):"Correct."));
if(x!=y){
printf("Try again.\n\n"),strcpy(str,"a");
}else{
printf("Would you wanna play again?(Y/N): "),scanf("%s",str);
str[0]|=32;
}
}while(strcmp(str,"n"));
//=====END=====//
system("PAUSE");
return 0;
}

2007-11-01 21:27:43 補充:
問題出在這裡:scanf("%c",&z);

這是迴圈遇到字元的弊病,任何迴圈都一樣。由於電腦讀取的是一連串的資料,讀到可以令電腦停止讀取的資料時,電腦就會等待使用者下達下一個指令。問題是,在 C 語言裡,在使用者輸入的部分,通常字元後面沒有結束字元,導致電腦重複讀取資料。

解決的辦法如下:
1. 改為輸入字串資料,再比較字串或字元。
2. scanf(" %c",&z); 在 %c 的前面加一個「空格 Space」即可。

2007-11-01 17:19:11 · answer #1 · answered by Big_John-tw 7 · 0 0

fedest.com, questions and answers