Re: [問題] 請問骰子的問題

看板C_and_CPP作者 (vinci)時間14年前 (2011/04/03 16:49), 編輯推噓1(109)
留言10則, 4人參與, 最新討論串3/3 (看更多)
我又重新修改了程式,將提示用語從rolldice()的函式提出來 放到每個執行rolldice()之前,發現問題出現在 while (gameStatus == CONTINUE){...} 這個迴圈,總是會重複列印提示用語。 #include <stdio.h> #include <stdlib.h> #include <time.h> enum Status {CONTINUE, WON, LOST}; int rollDice (void); int dice; int main () { int sum; int mypoint; enum Status gameStatus; /*gameStatus can contain CONTINUE, WOW, LOST*/ srand(time(NULL)); printf("Enter 'd' to dice:"); sum = rollDice(); switch (sum) { case 7: case 11: gameStatus = WON; break; case 2: case 3: case 12: gameStatus = LOST; break; default: gameStatus = CONTINUE; mypoint = sum; printf ("Your point is %d\n", mypoint); break; } while (gameStatus == CONTINUE) { printf("Enter 'd' again to dice:"); sum = rollDice(); if (sum == mypoint) { gameStatus = WON; } else { if (sum == 7) { gameStatus = LOST; } } } if (gameStatus == WON) { printf("YOU WIN!!\n"); } else { printf("YOU LOST!!!\n"); } return 0; } int rollDice (void) { int dice1 = 0; int dice2 = 0; int dice_sum = 0; dice = getchar(); while (dice == 'd'){ dice1 = 1 + (rand() % 6); dice2 = 1 + (rand() % 6); dice_sum = dice1 + dice2; printf ("Your sum are %d + %d = %d\n", dice1, dice2, dice_sum); break; } return dice_sum; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.76.74.83

04/03 16:52, , 1F
在 dice = getchar(); 下面再加一行 getchar();
04/03 16:52, 1F

04/03 16:52, , 2F

04/03 17:15, , 3F
Oh yeah!可以耶!!why?
04/03 17:15, 3F

04/03 17:16, , 4F
推 LPH66:這是換行字元問題 ←上一篇推文就有說了
04/03 17:16, 4F

04/03 17:16, , 5F
因為你輸入了 d ENTER, 第一次的 getchar 只會吃掉 d
04/03 17:16, 5F

04/03 17:16, , 6F
而第二次的 getchar 吃到 ENTER 之後就繼續執行,不會停
04/03 17:16, 6F

04/03 17:17, , 7F
我加上一個 getchar 便是為了解決那個 ENTER
04/03 17:17, 7F

04/03 17:27, , 8F
改版後的程式碼就用貼code連結, 不需要再回文.
04/03 17:27, 8F

04/03 17:30, , 9F
同感
04/03 17:30, 9F

04/03 19:07, , 10F
感謝啦!學到了!!
04/03 19:07, 10F
文章代碼(AID): #1Dc3I8q- (C_and_CPP)
文章代碼(AID): #1Dc3I8q- (C_and_CPP)