我正在尝试创建一个程序,该程序根据用户输入的最大值将随机数相乘

I am trying to create a program that multiplies random numbers based on a maximum the user inputs

本文关键字:程序 输入 用户 最大值 随机数 创建 一个      更新时间:2023-10-16

我还不是很擅长这个,我正在尝试学习如何让用户声明的变量在我的方程中工作。现在,我只想让计算机根据用户指定的最大数量吐出随机乘法。

当我尝试运行它时,机器会吐回这些错误:

12:16: error: ambiguous overload for 'operator>>' in 'std::cin >> 32767'
14:61: error: 'x' was not declared in this scope
14:64: error: 'y' was not declared in this scope
15:16: error: statement cannot resolve address of overloaded function
20:9: error: declaration of 'int x' shadows a parameter
21:5: error: expected ',' or ';' before 'int

最终目标是计算机将在难度参数中生成问题,然后删除方程中的一个变量来测验用户。

#include <cstdlib>
#include <iostream>
using namespace std;
int mult( int x, int y );
int main()
{
    cout <<"Please enter a number between 2 and 21, this will determine how difficult your problems are.";
    cin >> RAND_MAX;
    cin.ignore();
    cout << "The product of your numbers is:" << mult ( x, y ) <<"n";
    cin.get;
}
int mult (int x, int y)
{
    int x = rand()
    int y = rand()
    return  x * y;
}

这里有不少错误。我会努力变得善良。

  1. 在两次rand()调用后都需要分号。
  2. xymain()的任何地方都没有声明。我不知道你为什么要将它们作为参数传递给mult(),但我认为会有一些相关的功能。
  3. RAND_MAX是一个常数,所以cin >> RAND_MAX没有意义。相反,请参阅@Bill的答案。
  4. cin.get后你需要括号.

这是一个工作示例,希望这是您希望它执行的操作:

#include <cstdlib>
#include <iostream>
using namespace std;
int mult( int x, int y, int randMax );
int main()
{
    int x = 0, 
        y = 0, 
        randMax;
    cout <<"Please enter a number between 2 and 21, this will determine how difficult your problems are.";
    cin >> randMax;
    cin.ignore();
    cout << "The product of your numbers is:" << mult ( x, y, randMax ) <<"n";
    cin.get();
}
int mult (int x, int y, int randMax)
{
    x = rand() % randMax;
    y = rand() % randMax;
    return  x * y;
}

其他人指出了诸如试图修改RAND_MAX等问题,期望这会改变rand()的运作方式。我只想展示如何使用现代<random>库代替rand()

有很多原因不使用 rand() .

对您的

情况最重要的原因是,使用它来正确获取所需范围内的值并不简单。人们最常见的方法是像rand() % randMax + 1,但对于大多数randMax值,这实际上会比其他数字更频繁地产生[1,randMax]范围内的一些数字。如果获得均匀分布的数字很重要,那么您需要更多类似的东西:

int v;
do {
  v = rand();
} while (v >= RAND_MAX / randMax * randMax);
v = v % randMax + 1;

这并不那么简单。 <random>提供了许多预制发行版,因此您通常不必像这样编写自己的发行版。

不使用rand()的其他原因是它在多线程程序中不是线程安全或易于使用的,而且通常它不是很随机。 <random>也可用于解决这些问题。

这是使用<random>的程序版本。

#include <random>
#include <iostream>
// global random number engine and distribution to use in place of rand()
std::default_random_engine engine;
std::uniform_int_distribution<> distribution;
int mult()
{
    int x = distribution(engine);
    int y = distribution(engine);
    return  x * y;
}
int main()
{
    std::cout << "Please enter a number between 2 and 21, this will determine how difficult your problems are.";
    int max;
    std::cin >> max;
    // set the global distribution based on max
    distribution.param(std::uniform_int_distribution<>(1,max).param());
    std::cout << "The product of your numbers is:" << mult() << "n";
}