给定一个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);
}
}
|
运行结果:
-[-/a>
|