![](/img/trans.png)
[英]Why does the compiler write a member variable to memory for each iteration of this loop?
[英]Why does this output 4 times for each ‘for’ iteration
我正在嘗試制作一個基本的計時器,此代碼似乎可以根據duration
的值正確打印出毫秒數
但是有人能告訴我為什么不管duration
的值是多少,它為每個“滴答”打印輸出4次,以及如何校正它,以便在duration
每個“滴答”設置中只輸出一次? 我敢肯定這一定是我所忽略的簡單事物,但我仍在學習C ++的基礎知識,但看不到錯誤。
我正在iOS“ Mobile C”應用程序上運行它,但我不認為那會導致問題。
#include <chrono>
#include <iostream>
int main()
{
using namespace std::chrono;
auto start = high_resolution_clock::now();
int duration = 100;
int i = 0;
while (i <= 100)
{
auto now = high_resolution_clock::now();
auto millis = duration_cast<milliseconds>(now - start).count();
if (millis % duration == 0)
{
std::cout << "millis: " << millis << std::endl;
i++;
}
}
}
由於我仍然很陌生,所以我無法發表評論,但是您獲得4次輸出的原因是,就像Jesper Juhl所說的那樣,如果機器上的那一毫秒if語句為4次,則為true。 考慮使用bool
確保其只運行一次。 就像是
bool hasRun = false;
if (millis % duration == 0)
{
if (!hasRun)
{
std::cout << "millis: " << millis << std::endl;
hasRun = true;
}
}
else
hasRun = false;
然后,您將能夠像注釋中提到的那樣保持無限的Arduino仿真循環,但每個duration
僅使該語句響一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.