我要做的是在多个文本文件中生成随机数,这是我当前的代码:
// Write files
string file_name_write = "2016\\Sem2\\Timetable_list\\Timetable" + s->Get_subid() + ".txt";
ofstream fo (file_name_write.c_str()); // E.g: Timetable_list\TimetableICT1.1.txt
fo << "Subject ID: " << s->Get_subid() << endl;
fo << "Subject name: " << s->Get_name() << endl;
fo << "Lecturer: " << s->lecturer << endl;
fo << "Venue: " << s->venue << endl;
fo << "Time: " << s->time << endl << endl;
fo << "List of students for this subject:" << endl;
fo << "Order ID Name DOB Address E.Year Major Midterm Final Total" << endl;
int n = s->number_of_students;
Student *temp_stu;
srand(time(NULL));
for (int i=0; i<n; i++)
{
int random_mid;
int random_final;
random_mid = (rand() % 20) + 1;
random_final = (rand() % 20) + 1;
temp_stu = lstu.Find_Student (s->stu_id[i]);
fo << i+1 << " " << temp_stu->Get_pid() << " " << temp_stu->Get_fname() << " "
<< temp_stu->Get_dob() << " " << temp_stu->Get_addr() << " "
<< temp_stu->Get_ent_year() << " " << temp_stu->Get_major() << " " << random_mid
<< " " << random_final << endl;
}
fo.close();
s = s -> next;
我遇到的问题是我的文本文件中的随机数列表完全相同。例如,我的每个文件都生成相同的数字:
Midterm Final
14 16
12 5
5 1
12 15
19 18
我希望我的程序在每个文本文件中生成不同的数字列表,任何想法我该怎么做?谢谢。
答案 0 :(得分:0)
调用时间(NULL)将返回秒,因此您的代码会在同一秒内使用相同的种子重新初始化PRNG。举个例子:
srand (33); // initialize with a fixed seed = 33.
printf ("random number: %d, %d, %d\n", rand()%100, rand()%100, rand()%100);
// > random number: 41, 15, 22
srand (33); // re-initialize with the same seed = 33.
printf ("random number: %d, %d, %d\n", rand()%100, rand()%100, rand()%100);
// > random number: 41, 15, 22
您必须在应用程序启动时初始化PRNG一次:
int main () {
srand(time(NULL));
... // other code