[問題] 單步執行是正確的,但執行結果是錯誤!?

看板C_and_CPP (C/C++)作者 (醉心)時間16年前 (2009/06/15 21:50), 編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/1
太久沒寫C++,突然遇到一個很奇怪的問題 就是單步執行時,是正常的,但是執行結果是錯誤 原以為是自己程式其他結構上的問題,但把其中一部分 拉出來寫成小程式來看,一樣會有這樣問題 = =" 應該是個小地方錯誤,麻煩大家幫忙看一下,謝謝! 附上我的小程式碼: #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; int test(); int main() { int i=0 ; int dec_I=0; for(i=0;i<10;i++) { if(test() ==1) dec_I++; } cout << dec_I << endl; system("pause"); } int test() { int x = 0; srand(time(NULL)); x = rand()%2; return x; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 124.8.145.5

06/15 21:52, , 1F
srand(time(NULL)); 這行請放在 main 的第一行
06/15 21:52, 1F

06/15 21:54, , 2F
謝謝!可以了
06/15 21:54, 2F

06/15 22:07, , 3F
cpu跑太快了,你跑了10次test()裡面取得的time()值都一樣
06/15 22:07, 3F
文章代碼(AID): #1ADb6l7g (C_and_CPP)
文章代碼(AID): #1ADb6l7g (C_and_CPP)