2随之而来的循环c ++奇怪的行为

时间:2016-01-04 20:40:32

标签: c++ loops while-loop

我在一个帖子中有以下代码 - 一些背景:它检查一个bool Binaryrunning然后降低或升高音量 - 虽然结果是我想要的,但有一些行为我不明白

maxvol为100,minvol为40的两个

while(threadrunning)
{
    curvol = music.getVolume();

    if(tgtvol!=curvol)
    {
        while(curvol<tgtvol)
        {
            curvol++;
            music.setVolume(curvol);
            std::cout<<"curvol is " << curvol << " tgtvol is " << tgtvol << std::endl;
            usleep(20000);
        }

        while(curvol>tgtvol)
        {
            curvol--;
            music.setVolume(curvol);
            std::cout<<"curvol is " << curvol << " tgtvol is " << tgtvol << std::endl;
            usleep(20000);
        }

        std::cout << "CURVOL IS " <<curvol <<std::endl;
    }

    if(Binaryrunning)
    {
        tgtvol=minvol;
    }
    else
    {
        tgtvol=maxvol;
    }

    usleep(TTWMS*2);
}

现在,如果curvol低于它输出的tgtvol

curvol is 98 tgtvol is 100
curvol is 99 tgtvol is 100
curvol is 100 tgtvol is 100
CURVOL IS 100

然后停止输出 - 一切都很好......

如果降低输出:

curvol is 41 tgtvol is 40
curvol is 40 tgtvol is 40
CURVOL IS 40
curvol is 40 tgtvol is 40
CURVOL IS 40

等等,但它应该只输出

curvol is 40 tgtvol is 40
CURVOL IS 40

一次,止步没有?我不明白吗?我看起来似乎很愚蠢,但我只是看不到它......

有人可以澄清这个吗?

0 个答案:

没有答案