问题
Here is the code, but the outputs aren't coming out random? Maybe cause when the program runs it has the same time as all the loops?
#include <iostream>
using namespace std;
#include <string>
#include <cmath>
#include <ctime>
#include <cstdlib>
int main()
{
long int x = 0;
bool repeat = true;
srand( time(0));
int r1 = 2 + rand() % (11 - 2); //has a range of 2-10
int r3 = rand();
for (int i = 0; i <5; i++)
{
cout << r1 << endl; //loops 5 times but the numbers are all the same
cout << r3 << endl; // is it cause when the program is run all the times are
} // the same?
}
回答1:
You need to move your calls to rand() to inside your loop:
#include <iostream>
using namespace std;
#include <string>
#include <cmath>
#include <ctime>
#include <cstdlib>
int main()
{
long int x = 0;
bool repeat = true;
srand( time(0));
for (int i = 0; i <5; i++)
{
int r1 = 2 + rand() % (11 - 2); //has a range of 2-10
int r3 = rand();
cout << r1 << endl; //loops 5 times but the numbers are all the same
cout << r3 << endl; // is it cause when the program is run all the times are
} // the same?
}
That said: since you're writing C++, you really want to use the new random number generation classes added in C++ 11 rather than using srand/rand at all.
回答2:
You must call rand() each loop iteration.
for (int i = 0; i <5; i++)
{
cout << 2 + rand() % (11 - 2) << endl;
cout << rand() << endl;
}
What was happening before was that you were calling rand() twice, one for r1 and once for r3, and then simply printing the result 5 times.
来源:https://stackoverflow.com/questions/22749167/srandtime0-not-making-random-numbers