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::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();
}
You shoud pay attention to operator precedence. Modulo operator
%has the same precedence as multiplication*. Therefore when you writec++ will interpret that as
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
where the extra parenthesis ensure the correct computation sequence.