c#随机生成一个150的整数,通过任意键盘输入,直到输入的数与随机数为好止
时间: 2024-02-01 14:13:51 浏览: 25
你可以使用以下代码实现这个功能:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int target = random.Next(1, 151);
int guess = 0;
Console.WriteLine("猜一个1到150之间的整数:");
while (guess != target)
{
string input = Console.ReadLine();
if (!int.TryParse(input, out guess))
{
Console.WriteLine("输入无效,请输入一个整数:");
continue;
}
if (guess < target)
{
Console.WriteLine("猜小了,再试一次:");
}
else if (guess > target)
{
Console.WriteLine("猜大了,再试一次:");
}
}
Console.WriteLine("恭喜你,猜对了!");
}
}
```
这段代码首先使用 `Random` 类生成一个 1 到 150 之间的随机整数,然后进入一个循环,要求用户输入一个整数,如果输入不是整数则提示用户重新输入,否则判断用户猜的数与随机数的大小关系,给出相应的提示,直到猜对为止。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)