[問題] 0~100猜數字問題

看板C_and_CPP作者 (★GY大★)時間15年前 (2010/04/25 19:01), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/1
小弟目前在寫一個猜數字的程式0~100 code如下 #include<stdio.h> #include<stdlib.h> #include<time.h> int main(void) { srand( (unsigned)time( NULL ) ); int num1; int a; char b; while(b!='n') { num1=rand()%100+1; printf("I have a number between 1 and 100.\n"); printf("Can you guess my number?\n"); printf("Please type your first guess.\n"); scanf("%d",&a); while(a!=num1) { if(num1>a) { printf("Too low. Try again.\n"); scanf("%d",&a); } if(num1<a) { printf("Too high. Try again.\n"); scanf("%d",&a); } } printf("Excellent! You guessed the number!\n"); printf("Would you like to play again (y or n)?\n"); scanf("%c",&b); } return 0; } 程式都可以執行,但是問題出在當我猜對之後,要輸入y或n來決定是否繼續玩時, 我的程式不給我輸入y或n,直接就繼續跑 I have a number between 1 and 100. Can you guess my number? Please type your first guess. 我連y都還沒輸入就直接跑出來了... 小弟看了一下,邏輯上好像也沒有錯 請高手指點一下 謝謝!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 210.64.150.147

04/25 19:22, , 1F
line 37的scanf("%c",&b);改成scanf(" %c",&b);
04/25 19:22, 1F

04/25 19:23, , 2F
原本的會讀到前一個輸入的'\n' 加空白可跳過前置空白字元
04/25 19:23, 2F

04/25 19:30, , 3F
OK了^^ 謝謝你!!
04/25 19:30, 3F
文章代碼(AID): #1Br23ipG (C_and_CPP)