首页 > 后端开发 > C++ > 编写一个C程序来进行猜数字游戏

编写一个C程序来进行猜数字游戏

WBOY
发布: 2023-09-11 08:41:09
转载
1079 人浏览过

编写一个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
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板