c#-随机数2

来源:互联网 发布:hbase不直接删除数据 编辑:程序博客网 时间:2024/05/01 10:46
/* 随机给出一个0~99(包括0和99)之间的数字,然后让你猜是什么数字。你可以随便猜一个数字,游戏会 提示太大还是太小从而缩小范围。经过几次猜错与提示,最终给出答案。 要求与提示:(1)采用控制台;(2)输入数字可能是非数值,应进行处理,并提示;(3)如果用户想提前结束游戏怎么办?(4)功能代码与输入输出代码分离。提示:使用Random类,创建Random类的实例,使用Next()方法生成随机数。 */using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            Random rd = new Random();            int num = rd.Next(0, 100);            try            {                Console.WriteLine("请输入要猜测的数:");                int a = Convert.ToInt32(Console.ReadLine());                MyClass.Cout(a, num);            }            catch (FormatException)            {                Console.WriteLine("必须输入数字!");            }                        Console.ReadKey();        }    }    class MyClass    {        public static void Cout(int a,int n)        {            while (a!=n)            {                string bo;                if (a < n )                {                    Console.WriteLine("太小!");                }                else if (a > n)                {                    Console.WriteLine("太大!");                }                else                {                     break;                }                Console.Write("是否继续(Y/N)?:");                bo = Console.ReadLine();                if (bo == "N")                {                    Console.WriteLine("游戏结束!");                    break;                }                try                {                    Console.WriteLine("请输入要猜测的数:");                    a = Convert.ToInt32(Console.ReadLine());                }                catch (FormatException)                {                    Console.WriteLine("必须输入数字!");                }            }            if(a==n)                Console.WriteLine("恭喜您,答对了!");        }    }}

运行结果:


0 0
原创粉丝点击