gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:03:55 25 4
gpt4 key购买 nike

所以我正在创建一个程序,我必须在其中创建具有随机数和运算符的随机问题集。我制作随机数没有问题。但是,我对如何随机化我需要使用的三个运算符(加法、减法和乘法)感到困惑。我知道我必须使用数字来表示这三个运算符,但我不知道该怎么做。我必须使用随机数生成器才能执行此操作以及 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com