C++ question this time.
I'm trying to store the product between two random numbers... It's supposed to be asking what the product between two random numbers that generate based on srand(time(0)), and quitting after -1 is entered...
The following is my code:
#include <iostream>
using std::cou开发者_如何转开发t;
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();
}
You shoud pay attention to operator precedence. Modulo operator %
has the same precedence as multiplication *
. Therefore when you write
rand()%10 * rand()%10
c++ will interpret that as
((rand()%10) * rand()) % 10
in other words the last modulo is applied to the result of everything else.
If you want to multiply two random numbers between 0 and 9 you should use instead
(rand() % 10) * (rand() % 10)
where the extra parenthesis ensure the correct computation sequence.
You are generating two random number to calculate the answer, and the other two different random numbers to ask the question. Chances are that they will be different!
So:
int a = rand()%10, b = rand()%10;
int random_int = a*b;
//...
cout << a << " multiplied by " << b <<"? \n";
BTW, your code has quite a few style defects...
- Do not call
srand()
from a function. Usually it should be called frommain
. - If a function returns
int
, then return anint
that means anything. If not, returnvoid
. - Check that the user input is valid:
if (!(cin >> x))
or similar. - Use
endl
consistently. - Why the
cout << ""
?. It looks like a Java idiom, but in C++ does nothing.
You are generating random numbers every time, not only every time you enter the loop but also when printing them to the screen. Besides the lack of an actual question, I assume you want to at least do something like this:
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;
If you want the random value to be the same in each iteration of the loop, simply move the definition and initialization of the random variables outside the loop.
精彩评论