编写一个 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+ 浏览

开启你的职业

通过完成课程获得认证

开始
广告