2015-10-14 47 views
-1

我試圖做的是生成多個文本文件的隨機數是什麼,這是我當前的代碼:生成多個文本文件的隨機數

// 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

難道這正在偶然循環\多個函數調用做了什麼? – NathanOliver

+1

@NathanOliver建議種子是在同一時間總是因爲'時間(...'有第二個分辨率? –

+0

不,不是。@NathanOliver – Marco

回答

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