標籤:執行個體 c 遊戲 while
為了練習使用do..while和while,特地使用此執行個體,一個簡單的猜數遊戲對while迴圈進行的練習使用。所有的東西都在注釋當中:
#include <stdio.h>#include <conio.h>/********************************** * 該執行個體用於實現一個簡單的猜數位遊戲 * 主要用於練習使用while迴圈 * 開始的時候需要使用者輸入遊戲密碼(1234) * 如果使用者輸入錯誤 * 則提示使用者重新輸入 * 如果三次輸入錯誤,則提示使用者退出程式 ***********************************/int main(void){ int passwd = 0,Number = 0,price = 58,i = 0; printf("\n====This is a Number Guess Game!====\n"); //提示資訊 while(passwd != 1234){ if(i >= 3) /*如果輸入錯誤次數大於3就退出*/ { printf("\n Please input the right password!\n"); return; } i++; puts("Please input Password: "); scanf("%d",&passwd); /*要求輸入密碼*/ } i = 0; while(Number != price){ do{ puts("Please input a number between 1 and 100: "); scanf("%d",&Number); printf("Your input number is %d\n",Number); }while(!(Number >= 1 && Number <= 100)); if(Number >= 90) /*輸入大於90的情況*/ { printf("Too Bigger!Press any key to try again!\n"); }else if(Number >= 70 && Number <= 90) /*比較大的情況*/ { printf("Bigger!\n"); }else if(Number >= 1 && Number <= 30) /*太小的情況*/ { printf("Too Small!Press any key to try again!\n"); }else if(Number > 30 && Number <= 50) /*比較小的情況*/ { printf("Small!! Press any key to try again!\n"); }else{ if(Number == price) { printf("OK! You are right!Bye Bye!\n"); }else if(Number < price){ printf("Sorry,Only a little smaller!Press any key to try again!\n"); }else if(Number > price) printf("Sorry,Only a little bigger!Press any key to try again!\n"); } getch(); } /***************************************************** * 1:一個比較經典的面試題目 * do,while和while的區別 * 根據學習,可以知道do..while能夠保證至少有一次運行。 * 2:常見的迴圈的應用 * 1).計數迴圈 * 2).輸入驗證迴圈 * 3).哨兵迴圈。迴圈程式不斷的檢查,讀和處理資料 * 4).延時迴圈。迴圈中不實現任何功能,只是使CPU * 等待一定時間後再繼續執行,在單片機程式中比較常用 * 5).尋找迴圈。按給定的對象進行尋找 * 6).無限迴圈,不停的執行。在危險訊號的檢測中經常用到 ****************************************************/ return 0;}
我的程式的輸出結果:
密碼是1234奧!!
C實現一個比較簡單的猜數遊戲