在一個程式中,一個數字已經被初始化為某個常數。在這裡,我們需要要求用戶猜測已經在程式中的數字。為此,我們需要為每次使用者輸入數字提供一些線索。
用來猜測數字的邏輯如下所示−
do{ if(num==guess){ flag=0; } else if(guess<num) { flag=1; printf("Your guess is lower than the number</p><p>"); count++; } else { flag=1; printf("Your guess is greater than the number</p><p>"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it</p><p>"); scanf("%d",&guess); } } while(flag);
以下是猜數字遊戲的C程式。
即時示範
#include<stdio.h> main() { int i,num=64,flag=1,guess,count=0; printf("guess the number randomly here are some clues later</p><p>"); scanf("%d",&guess); do { if(num==guess) { flag=0; } else if(guess<num) { flag=1; printf("Your guess is lower than the number</p><p>"); count++; } else { flag=1; printf("Your guess is greater than the number</p><p>"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it</p><p>"); scanf("%d",&guess); } } while(flag); printf("Congratulations! You guessed the correct number %d</p><p>",num); printf("Total number of trails you attempted for guessing is: %d</p><p>",count); }
當上述程式執行時,它產生下列輸出 −
guess the number randomly here are some clues later 45 Your guess is lower than the number sorry wrong enter! once again try it 60 Your guess is lower than the number sorry wrong enter! once again try it 70 Your guess is greater than the number sorry wrong enter! once again try it 65 Your guess is greater than the number sorry wrong enter! once again try it 62 Your guess is lower than the number sorry wrong enter! once again try it 64 Congratulations! You guessed the correct number 64 Total number of trails you attempted for guessing is: 5
以上是編寫一個C程式來進行猜數字遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!