本文实例为大家分享了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为止。
代码实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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); } } |
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/cx_fd520/article/details/104629673?depth_1-utm_source=distribute.pc_category.none-task&request_id=&utm_source=distribute.pc_category.none-task