看板 C_and_CPP 關於我們 聯絡資訊
小弟新手,最近才剛開始學習 現在練習到一題骰子骰了100次 骰到1的有幾次,骰到2的有幾次.......骰到6的有幾次 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int r; int a1 = 0; int a2 = 0; int a3 = 0; int a4 = 0; int a5 = 0; int a6 = 0; for (int i = 1 ; i <= 100 ; i++) { srand(time(NULL)); r = 1 + rand()%(6-1+1); //隨機產生1~6 if (r==1) //骰到1的 { a1+=1; } else if(r==2) //骰到2的 { a2+=1; } else if(r==3) //骰到3的 { a3+=1; } else if(r==4) //骰到4的 { a4+=1; } else if(r==5) //骰到5的 { a5+=1; } else //骰到6的 { a6+=1; } } cout << a1 << endl << a2 << endl << a3 << endl << a4 << endl << a5 << endl << a6 << endl; system("PAUSE"); return 0 ; } 不知道哪裏出錯....亂數好像都一樣 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.204.126.57 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1449238031.A.3EB.html
james732: srand(time(NULL)); 放錯地方 12/04 22:08
akka5678: 哦哦~~謝謝,請問放在迴圈裡為什麼不行? 12/04 22:13
noodleT: 先照1f說的試試看 12/04 22:40
akka5678: 有,放在迴圈前就正常了 12/04 22:53
SiNcSaD: 想當初大一也問過老師這問題哈哈 12/04 23:56
overhead: Google srand就有原理說明 12/05 00:05
Leadgen: 迴圈每次時間都很快,下一輪時"時間種子"還是一樣。 12/05 07:14
Leadgen: 所以有固定的某段輸出,導致不Random。 12/05 07:15
zxc1234529: srand(time(NULL))以秒為單位(從1970年至今的秒數) 12/07 21:37