温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#如何实现猜数字游戏

发布时间:2021-05-17 09:37:59 来源:亿速云 阅读:384 作者:小新 栏目:编程语言

这篇文章主要介绍了C#如何实现猜数字游戏,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

给定一个0-100的随机数字猜其大小

题目样式:

电脑产生一个0到100之间的随机数字,并且要求用户来猜,如果用户猜的数字比这个数字大,电脑会提示“太大”,否则提示“太小”,当用户正好猜中,电脑会提示“恭喜你猜对了,这个数是·······”。在用户每次猜测之后,程序会输出是用户第几次猜测,如果用户输入的根本不是一个数字,程序会告诉用户输入无效。

提示:

产生0到100之间的随机数字可以用以下语句;
Random rdm = new Random();
int guess = rdm.Next(0, 101);

思路:

先设一个开关,是否要执行,是就输入“1”,否则的话输入“0”。然后根据这个随机数字guess,用户输入的的值赋值给input,用do…while语句判断guess与input的大小,直到找到input=guess为止。

代码实现:

class Program
  {
    static void Main(string[] args)
    {
      string i = null;
      do
      {
        Console.WriteLine("please input a numble between zero to hundred to guess.if you want to output,please input 0,else input 1.");
        i = Console.ReadLine();
        if(i.Trim().Equals("0"))
        {
          return;
        }
      } while (!i.Trim().Equals("1"));
      Random rdm = new Random();
      int guess = rdm.Next(0, 101);
      int input = 0;
      int j = 0;
      do
      {
        Console.WriteLine("please input a numble to guess.");
         i = Console.ReadLine();
        if(!int.TryParse(i,out input))
        {
          continue;
        }
        j=j+1;
        if (input > guess)
        {
          Console.WriteLine("this numble is too big,guess again please!");
          Console.WriteLine("this is {0} guess!", j);
        }
        else if (input < guess)
        {
          Console.WriteLine("this numble is too small,guess again please!");
          Console.WriteLine("this is {0} guess!", j);
        }

      } while (input != guess);
       Console.WriteLine("Congrtulations to you,you are guess right!this right numble is"+input);
    }
  }

运行结果:

C#如何实现猜数字游戏

感谢你能够认真阅读完这篇文章,希望小编分享的“C#如何实现猜数字游戏”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI