随机产生1~100以内的加减运算题,要求用户输入答案,然后系统显示出正确答案
时间: 2024-10-25 17:12:32 浏览: 61
20以内加法运算自动生成器
要实现这个功能,我们可以使用C++编写一个简单的控制台程序。这里我会提供一个基本的示例,包括生成随机数、计算答案以及获取用户的输入。我们将用到`<iostream>`(输入输出流)和`<cstdlib>`(包含`rand()`和`srand()`函数)库。
首先,我们需要设置随机数种子:
```cpp
#include <iostream>
#include <cstdlib>
// ... (后续代码)
std::srand(std::time(0)); // 设置随机数种子,保证每次运行结果不同
```
接下来,我们生成两个1到100之间的随机整数用于加减运算:
```cpp
int num1 = std::rand() % 100 + 1;
int num2 = std::rand() % 100 + 1;
```
然后选择一个随机操作符(加或减):
```cpp
int operator_choice = rand() % 2; // 0代表加法,1代表减法
char op;
if (operator_choice == 0) {
op = '+';
} else {
op = '-';
}
```
现在我们构造题目并获取用户的输入:
```cpp
std::cout << "What is the result of " << num1 << " " << op << " " << num2 << "? ";
std::cin >> answer;
```
最后,我们检查用户的答案是否正确,并给出结果:
```cpp
int correct_answer;
if (op == '+') {
correct_answer = num1 + num2;
} else { // 减法
correct_answer = num1 - num2;
}
if (answer == correct_answer) {
std::cout << "Correct!" << std::endl;
} else {
std::cout << "Incorrect, the correct answer is " << correct_answer << "." << std::endl;
}
```
完整代码如下:
```cpp
#include <iostream>
#include <cstdlib>
int main() {
std::srand(std::time(0)); // 设置随机数种子
int num1 = std::rand() % 100 + 1;
int num2 = std::rand() % 100 + 1;
int operator_choice = rand() % 2;
char op;
if (operator_choice == 0) {
op = '+';
} else {
op = '-';
}
int answer;
std::cout << "What is the result of " << num1 << " " << op << " " << num2 << "? ";
std::cin >> answer;
int correct_answer;
if (op == '+') {
correct_answer = num1 + num2;
} else {
correct_answer = num1 - num2;
}
if (answer == correct_answer) {
std::cout << "Correct!" << std::endl;
} else {
std::cout << "Incorrect, the correct answer is " << correct_answer << "." << std::endl;
}
return 0;
}
```
阅读全文