我嘗試計算通過循環做了多少次操作1秒。 爲此,我記得當我開始計算循環並在每次迭代中檢查時間時。 我的想法 - 當這兩個timemoments的秒數不同時,我printf做了多少循環迭代。錯誤與參考C++
這裏是我的代碼:
#include <ctime>
int main()
{
// For timing
time_t t, tstep;
struct tm* now, *step;
// this time will change at every iteration
t = time(0);
now = localtime(&t);
// save time of the start moment
tstep = t;
step = localtime(&tstep);
// counter of loop cycles
int count = 0;
for (size_t i = 0; i < 1e100 ; i++)
{
// ... here is some calculations
t = time(0);
now = localtime(&t);
count++;
if (now->tm_sec != step->tm_sec)
{
tstep = time(0);
step = localtime(&tstep);
//printf("number of lines %i \n", count);
count = 0;
}
}
return 0;
}
是什麼問題:我每次刷新now
step
成爲相同的值!而t
和tstep
是不同的!
看起來像這是因爲引用:也許當我使用tstep = t
這意味着這個變量的地址是指t
都。因此更改t
更改now
和tstep
。
如何解決這個問題?如何將t
的值複製到step
?或者還有另一種實際的方式?
如果你downvote,你能解釋爲什麼嗎? –
「_像這樣看是因爲參考_」你是**不**在代碼中的任何地方使用引用。 –
此外,這不是[最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve) – kim366