[問題] 有關rand()問題

看板C_and_CPP作者 (DRAGON)時間8年前 (2016/05/20 15:16), 8年前編輯推噓1(105)
留言6則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) code::blocks 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 寫了一個class Matrix,主要是希望產生矩陣,矩陣內的elements是由亂數產生 目前遇到的問題是在主程式宣告兩個Matrix A,B,分別呼叫member function 可是兩個矩陣內的elements都一樣。 餵入的資料(Input): 預期的正確結果(Expected Output): 矩陣A和矩陣B內由亂數產生的elements應該要不同。 錯誤結果(Wrong Output): 矩陣A和矩陣B內的值一模一樣。 程式碼(Code):(請善用置底文網頁, 記得排版) class Matrix { private: int dim; int **Array; public: void assignDimension(int n); void assignElements(); void printMatrix(); }; void Matrix::assignDimension(int n) { dim = n; } void Matrix::assignElements() { srand(time(NULL)); Array = new int *[dim]; for(int row = 0;row < dim;row++) Array[row] = new int [dim]; for(int i = 0;i < dim;i++) { for(int j = 0;j < dim;j++) *(Array[i] + j) = rand() % 10 + 1; } } void Matrix::printMatrix() { .......; } int main() { int n; cout << "Enter n for n x n matrix: "; cin >> n; Matrix A, B; A.assignDimension(n); A.assignElements(); cout << "A = "; A.printMatrix(); cout << endl; B.assignDimension(n); B.assignElements(); cout << "B = "; B.printMatrix(); cout << endl; return 0; } 補充說明(Supplement): 初學C++,想了很久不知哪裡出問題><,麻煩板上大大,謝謝。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 120.127.238.94 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1463728569.A.C89.html ※ 編輯: nick982009 (120.127.238.94), 05/20/2016 15:17:09

05/20 15:18, , 1F
常見錯誤,srand() 放在 main 裡就好,不要 call 兩次
05/20 15:18, 1F

05/20 16:51, , 2F
srand要放main裡,不是要用的時候才在函式裡call
05/20 16:51, 2F

05/20 17:15, , 3F
挺有趣的 竟然是在寫class的時候碰上 應該是原po本來
05/20 17:15, 3F

05/20 17:15, , 4F
有些非c語言的基礎跳來直接學進階的用法
05/20 17:15, 4F

05/20 17:26, , 5F
srand()種子給一次就好了,你這樣其實是用到同一個種子。
05/20 17:26, 5F

05/20 22:55, , 6F
感謝樓上解答!!大學學C,程式經驗很少,努力複習中QQ
05/20 22:55, 6F
文章代碼(AID): #1NFhcvo9 (C_and_CPP)