I am brand new to this and for the life of me cannot figure out why this keeps printing out every answer. I want to create a random number generator which then displays the corresponding message to 1,2,and 3. Any help would be greatly appreciated. Thank you.
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int z;
for (int x = 1; x<2; x++){
1+(rand()%3)==z;
}
if (z = 1){
cout << "Random number generator produced the number 1" << endl;
}
if (z =2){
cout << "The number 2 has been generated." << endl;
}
if (z=3){
cout << "The number generator has produced the number 3." << endl;
}
return 0;
}
You've got the assignment (=) and equality(==) operators reversed.
Assign the random number to z. (Assignment takes the value of the expression on the right side of the operator and assigns it to the variable on the left side.) z = 1+(rand()%3);
Then you want to see if z is equal to 1,2 or 3. if (z == 1) (same for the other two)
Thank you very much for the tip. I am now getting one answer but it always seems to be for 3. Anymore tips? I have posted the revised code below, and thank you again very much for the quick response :)
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int z;
for (int x = 1; x<2; x++){
z=1+(rand()%3);
}
if (z == 1){
cout << "Random number generator produced the number 1" << endl;
}
if (z ==2){
cout << "The number 2 has been generated." << endl;
}
if (z==3){
cout << "The number generator has produced the number 3." << endl;
}
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
int z;
srand(time(0));
for (int x = 1; x<10; x++)
{
z=1+(rand()%3);
if (z == 1)
cout << "Random number generator produced the number 1." << endl;
elseif (z ==2)
cout << "Random number generator produced the number 2." << endl;
elseif (z==3)
cout << "Random number generator produced the number 3." << endl;
}
return 0;
}
Random number generator produced the number 1.
Random number generator produced the number 2.
Random number generator produced the number 3.
Random number generator produced the number 1.
Random number generator produced the number 1.
Random number generator produced the number 3.
Random number generator produced the number 1.
Random number generator produced the number 2.
Random number generator produced the number 3.
Perfect! Thank you, thank you, thank you! I have been racking my brain for ages and reviewing material and some how completely forgot about "srand". I really appreciate the help.