編寫一個 C 語言猜數遊戲程式。


問題

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

解決方案

用於猜測數字的邏輯如下 −

do{
   if(num==guess){
      flag=0;
   } else if(guess<num) {
      flag=1;
      printf("Your guess is lower than the number
");       count++;    } else {       flag=1;       printf("Your guess is greater than the number
");       count++;    } if(flag==1) {       printf("sorry wrong enter! once again try it
");       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
");    scanf("%d",&guess);    do {       if(num==guess) {          flag=0;       } else if(guess<num) {          flag=1;          printf("Your guess is lower than the number
");          count++;       } else {          flag=1;          printf("Your guess is greater than the number
");          count++;       }       if(flag==1) {          printf("sorry wrong enter! once again try it
");          scanf("%d",&guess);       }    } while(flag);    printf("Congratulations! You guessed the correct number %d
",num);    printf("Total number of trails you attempted for guessing is: %d
",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

更新於: 2021-03-25

1K+ 瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告