编写一个猜数字小游戏,让系统产生一个随机的两位数,由用户去猜 c#
时间: 2024-11-22 15:41:59 浏览: 40
在C#中编写一个简单的猜数字游戏,可以按照以下步骤进行:
```csharp
using System;
using System.Random;
class GuessNumberGame
{
private const int MIN_NUMBER = 10;
private const int MAX_NUMBER = 99;
private Random random = new Random();
private int secretNumber;
public void Start()
{
// 生成随机数
secretNumber = random.Next(MIN_NUMBER, MAX_NUMBER + 1);
Console.WriteLine("欢迎来到猜数字游戏!我想了一个介于 {0} 和 {1} 之间的两位数,试试看你能猜几次猜对吧!", MIN_NUMBER, MAX_NUMBER);
while (true)
{
Console.Write("请输入你猜测的数字:");
string input = Console.ReadLine();
int guess = int.Parse(input);
if (guess < secretNumber)
{
Console.WriteLine("太小了,再试一次!");
}
else if (guess > secretNumber)
{
Console.WriteLine("太大了,再想想!");
}
else
{
Console.WriteLine($"恭喜你,猜对了!秘密数字就是 {secretNumber}。");
break;
}
}
}
static void Main(string[] args)
{
GuessNumberGame game = new GuessNumberGame();
game.Start();
}
}
阅读全文