用C++写随机生成一个范围在【1,100】的整数,;设计一个猜数的游戏,请遵守以下规则:1.生成随机数,并提示随机数已生成 2.每次输入一个数字,若不正确,则提示太大(小)了; 3.最多猜10次,若未猜出数字,则输出失败,并输出随机数; 4.若猜中数字,则输出猜对了,并统计次数
时间: 2024-10-21 22:02:24 浏览: 33
在C++中,我们可以使用 `<cstdlib>` 和 `<ctime>` 库来生成随机数,以及 `<iostream>` 来处理用户输入。下面是一个简单的猜数游戏程序的示例:
```cpp
#include <iostream>
#include <cstdlib> // for rand and srand
#include <ctime> // for time
int main() {
srand(time(0)); // 设置随机数种子,保证每次运行结果不同
int targetNumber = std::rand() % 100 + 1; // 生成1到100之间的随机整数
std::cout << "随机数已生成:" << targetNumber << "\n";
int guess;
int attempts = 0;
do {
std::cout << "请输入你猜测的数字 (1-100): ";
std::cin >> guess;
attempts++;
if (guess < targetNumber) {
std::cout << "太小了!\n";
} else if (guess > targetNumber) {
std::cout << "太大了!\n";
}
} while (guess != targetNumber && attempts <= 10);
if (guess == targetNumber) {
std::cout << "恭喜你,猜对了!你总共尝试了 " << attempts << " 次。\n";
} else {
std::cout << "很遗憾,你输了。随机数是 " << targetNumber << ".\n";
}
return 0;
}
```
在这个程序中,我们首先生成了一个1到100的随机数,然后让用户输入猜测。如果猜测不正确,我们会给出提示,直到他们猜中或者达到10次限制。如果猜中,会显示猜测次数;如果没有猜中,会直接显示正确的随机数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)