c++ - 在 C++ 中生成随机数学运算符

标签 c++

所以我正在创建一个程序,我必须创建具有随机数和运算符的随机问题集。我制作随机数没有问题。但是,我对如何随机化需要使用的三个运算符(加法、减法和乘法)感到困惑。我知道我必须使用数字来表示这三个运算符,但我不明白该怎么做。我必须使用随机数生成器才能执行此操作以及 If & Then 语句。这是我的源代码。

我尝试创建一个名为“const int MAXOP_VALUE = 3”的单独常量。我被困在之后该做什么。如何将加法、减法和乘法运算符表示为数字?

#include "pch.h"
#include <iostream>
#include <iomanip>
#include <cmath>  
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
/*Constants*/
const int MIN_VALUE = 1;
const int MAX_VALUE = 100;

/*Variables*/
int number_1;
int number_2;
int math_op;

/*Get the System Time*/
unsigned seed = time(0);

/*Seed the Random Number Generator*/
srand(seed);

/*Generates Random Numbers for the Math Problems*/
number_1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
number_2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;

/*Answer to Problem*/


/*Explains How the Program Works*/
cout << "****************************************" << endl << endl;
cout << "Welcome to the awesome math tutor! \n";
cout << "Get ready to add, subtract, and multiply!" << endl << endl;
cout << "****************************************" << endl << endl;
cout << "How much is" << number_1 << math_op << number_2 << "?" << 
endl;


return 0; 
}

我希望输出是这样的: “25+42是多少?” “54*3 是什么?” “76-2 是什么?”

最佳答案

一个用于生成随机math_op的衬垫。删除 int math_op 并将此行放在 srand(seed) 之后的某个位置。

char math_op = "+-*"[rand() % 3];

并且您可以使用switch-case语句进行实际计算。

关于c++ - 在 C++ 中生成随机数学运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603093/

相关文章:

c++ - 程序在 rc.d 脚本启动后终止 (Arch Linux)

c++ - 观察者设计模式及其他

c++ - FindFirstFile、FindNextFile API 是否不可靠?

c++ - 对 gsl 的 undefined reference

c++ - 扑克算法手评估器

c++ - Qt中类成员变量的内存管理

c++ - 在 msvs2010 上使用 curl 编译项目

c++ - 为 TCP 套接字服务器编写代码时,用于多个异步连接的最佳库 (C/C++) 是什么?

C++ std::deque 复制构造函数问题

c++ - const 成员堆栈与堆