【发布时间】:2019-10-24 06:03:43
【问题描述】:
当变量“持续时间”达到 5 秒时,我想退出 While 循环。
变量“持续时间”总是=0
#include <iostream>
#include <Windows.h>
#include <chrono>
using namespace std;
DOUBLE duration;
int main()
{
using clock = std::chrono::system_clock;
using sec = std::chrono::duration <double>;
const auto before = clock::now();
while (duration < 5.0)
{
const auto after = clock::now();
const sec duration = after - before;
std::cout << "It took " << duration.count() << "s" << std::endl;
}
std::cout << "After While Loop "; //Never reaches this line!!!!!
return 0;
}
实际输出:.
.
花了 9.50618 秒
它工具 9.50642s
.
我预计 while 循环会在 5.0 或更高版本退出。
显示变量始终显示 0。
【问题讨论】:
-
duration您正在打印的是该循环的本地。虽然您正在签入的durationwhile循环是不同的 -
您的“实际输出”看起来不像是所示代码的输出。
-
被忽视Variable shadowing的经典案例
-
谢谢大家。它有效。
标签: c++ while-loop duration