I am having trouble grasping the concept of rand() and srand() in c++. I need to create a program that displays two random numbers, have the user enter a response, then match the response with a message and do this for 5 times.
My question is how do I use it, the instructions say I can't use the time() function and that seems to be in every tutorial online about rand().
this is what I have so far.
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int seed;
int response;
srand(1969);
seed=(rand()%10+1);
cout<<seed<<" * "<<seed<<" = ";
cin>>response;
cout<<response;
if(response==seed*seed)
cout<<"Correct!. you have correctly answered 1 out of 1."<<endl;
else
cout<<"Wrong!. You have correctly answered 0 out of 1."<<endl;
This just outputs something like 6*6 or 7*7, I thought the seed variable would be not necessary different but not the same all the time?
This is what the output should look like:
3 * 5 =
34
Wrongo. You have correctly answered 0 out of 1.
8 * 1 =
23
Wrongo. You have correctly answered 0 out of 2.
7 * 1 =
7
Correct! You have correctly answered 1 out of 3.
2 * 0 =
2
Wrongo. You have correctly answered 1 out of 4.
8 * 1 =
8
Correct! You have correctly answered 2 out of 5.
Final Results: You have correctly answered 2 out of 5 for a 40% average.
and these are the requirements:
Your program should use rand() to generate pseudo-random numbers as needed. You may use srand() to initialize the random number generator, but please do not use any 'automatic' initializer (such as the time() function), as those are likely to be platform dependent. Your program should not use any loops.
The way you are using it now seems fine. The reason why all the tutorials use time()
is because the numbers will be different every time you run your program. So, if you use a fixed number, every time your program runs, the output (number generation) will be the same. However, according to your requirements this doesn't seem to be a problem (if you need the random generation to be different every time you run your program, please specify that in your question).
However, rand()%10+1
is a range from 1 to 10
and not 0 to 10
like you want.
AFTER EDITS
To get the desired output, all you need is to make two seeds like so:
seed1=(rand()%11);
seed2=(rand()%11);
cout<<seed1<<" * "<<seed2<<" = ";
Also, you can ask the user for a seed
and then pass that to srand
to make each run more random.
About the requirements:
please do not use any 'automatic' initializer (such as the time() function), as those are likely to be platform dependent
std::time
is a standard C++ function in the <ctime>
header. I do not understand why it matters if the result is platform dependent.
Your program should not use any loops.
This is also a very strange requirement. Loops are fundamental building blocks of any program. The requirements seem very strange to me, I would ask your professor or teacher for clarification.