首頁 > 後端開發 > C++ > 編寫一個C程式來進行猜數字遊戲

編寫一個C程式來進行猜數字遊戲

WBOY
發布: 2023-09-11 08:41:09
轉載
1080 人瀏覽過

編寫一個C程式來進行猜數字遊戲

問題

在一個程式中,一個數字已經被初始化為某個常數。在這裡,我們需要要求用戶猜測已經在程式中的數字。為此,我們需要為每次使用者輸入數字提供一些線索。

解決方案

用來猜測數字的邏輯如下所示−

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);
登入後複製

Example

以下是猜數字遊戲的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中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板