无法退出While循环

问题描述 投票:0回答:3

当变量“持续时间”达到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。

c++ while-loop duration
3个回答
2
投票

您正在使用两个单独的名为duration的变量。]​​>

using sec = std::chrono::duration <double>; // number 1
const auto before = clock::now();
while (duration < 5.0) // checking number 1, which is not changed during looping    
{
    const auto after = clock::now();
    const sec duration = after - before; // number 2, created afresh in each iteration 
    std::cout << "It took " << duration.count() << "s" << std::endl;

}

因此,您要在循环条件中检查的不是在循环主体中更改的内容。


1
投票

您有两个称为持续时间的变量:


0
投票

声明与全局变量同名的局部变量会使它们成为两个独立的实体,这可能会引起混乱。

© www.soinside.com 2019 - 2024. All rights reserved.