无法退出While循环

时间:2019-10-24 06:03:43

标签: c++ while-loop duration

当变量“持续时间”达到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.50618s
   it工具9.50642s
   。
   我希望while循环在5.0或更高版本时退出。

显示变量始终显示0。

3 个答案:

答案 0 :(得分:3)

您正在使用两个名为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 :(得分:3)

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

DOUBLE duration;

和在while循环中:

const sec duration = after - before;

在评估while语句期间,您正在检查从未设置或更改的第一个语句。 在while循环体内,您正在创建一个隐藏全局变量的新变量。参见https://en.wikipedia.org/wiki/Variable_shadowing

在Insead中,您不应该声明一个新变量,而应使用声明的变量,然后再进入while循环。

答案 2 :(得分:3)

这里有两个问题:

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

  2. 您正在比较duration变量,该变量实际上是类sec对象不是整数或浮点数。因此,为了比较duration中的值,只需执行duration.count()以使其与整数或浮点值可比。

在这里,在您的代码中,全局duration变量永远不会更改,因为您在while循环中声明了一个新变量。在while条件中检查的duration变量是全局duration变量,但您希望它是循环内的duration变量。

有两种可能的解决方案:

  1. 使两个duration变量相同。

  2. 或者当while(1)变量的值为duration时中断>= 5循环,

解决方案1的代码如下:

#include <iostream>
#include <Windows.h>
#include <chrono>

using namespace std;

int main()
{

    using clock = std::chrono::system_clock;
    using sec = std::chrono::duration <double>;
    sec duration;
    const auto before = clock::now();
    while (duration.count() < 5.0)
    {
        const auto after = clock::now();
        duration = after - before;
        std::cout << "It took " << duration.count() << "s" << std::endl;
    }
    std::cout << "After While Loop ";  //Never reaches this line!!!!!
    return 0;
}

解决方案2的代码如下:

#include <iostream>
#include <Windows.h>
#include <chrono>

using namespace std;

int main()
{

    using clock = std::chrono::system_clock;
    using sec = std::chrono::duration <double>;
    const auto before = clock::now();
    while (1) // Soln 1: while(1)
    {
        const auto after = clock::now();
        const sec duration = after - before;
        std::cout << "It took " << duration.count() << "s" << std::endl;
        if(duration.count() >= 5) 
            break;
    }
    std::cout << "After While Loop ";  //Never reaches this line!!!!!
    return 0;
}