C ++存储两个随机数的乘积

时间:2011-10-13 21:51:40

标签: c++ variables random

这次是C ++问题。

我正在尝试将产品存储在两个随机数之间...它应该是在输入基于srand(time(0))生成的两个随机数之间的乘积,然后输入-1之后退出。 ..

以下是我的代码:

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;

#include <cstdlib>
using std::rand;
using std::srand;

#include <ctime>
using std::time;

int multiplication()
{
    srand( time(0));
    int x = 0;

    while (x != -1)
    {
        int random_int;
        random_int = (rand()%10 * rand()%10);
        cout << "(Enter -1 to quit) \n";
        cout << "" << rand() % 10 << " multiplied by " << rand() % 10 <<"? \n";
        cin >> x;

        if(x == random_int)
        {
            cout << "you're right!" << endl;
        }
        else
        {
            cout << "you're wrong" << endl;
        }
    }
    return 0;
}

int main()
{
    multiplication();
}

3 个答案:

答案 0 :(得分:3)

您正在生成两个随机数来计算答案,另外两个不同的随机数来提问。他们可能会有所不同!

所以:

int a = rand()%10, b = rand()%10;
int random_int = a*b;
//...
cout << a << " multiplied by " << b <<"? \n";
顺便说一下,你的代码有很多样式缺陷......

  • 不要从函数中调用srand()。通常应该从main
  • 调用它
  • 如果函数返回int,则返回int,这意味着什么。如果没有,请返回void
  • 检查用户输入是否有效:if (!(cin >> x))或类似。
  • 始终使用endl
  • 为什么cout << ""?它看起来像一个Java习语,但在C ++中什么都不做。

答案 1 :(得分:3)

你应该注意运营商的优先权。模运算符%与乘法*具有相同的优先级。因此,当你写

rand()%10 * rand()%10

c ++将其解释为

((rand()%10) * rand()) % 10

换句话说,最后一个模数应用于其他所有的结果。

如果你想在0到9之间乘以两个随机数,你应该使用

(rand() % 10) * (rand() % 10)

其中括号确保正确的计算顺序。

答案 2 :(得分:2)

您每次都会生成随机数,不仅是每次进入循环,还会将其打印到屏幕上。除了缺乏实际问题外,我假设你至少想做这样的事情:

    int random_digit_1 = rand()%10, random_digit_2 = rand()%10;
    int random_int = random_digit_1 * random_digit_2;

    cout << "(Enter -1 to quit) \n";
    cout << "" << random_digit_1 << " multiplied by " << random_digit_2 <<"? \n";
    cin >> x;

如果你想在循环的每次迭代中随机值相同,只需在循环外移动随机变量的定义和初始化。

相关问题