在C中每轮减少1%的INT

时间:2017-07-25 03:12:12

标签: c loops

如何每次减少10%的int(用于延迟时间)? 这是我目前的概念,我希望改进这一点。

void lights()
{
    light1(on);
    delay(50000);
    light1(off);
    delay(50000);
    light2(on);
    delay(50000);
    light2(off);
    delay(50000);

    light1(on);
    delay(40000);
    light1(off);
    delay(40000);
    light2(on);
    delay(40000);
    light2(off);
    delay(40000);

    delay(30000);
    delay(20000);
    delay(10000);
    delay(9000);
    delay(8000);
    all the way to like delay(100);
}

每次开灯/关灯后,它可以将延迟减少10%。 我不确定如何解决这个问题我尝试使用谷歌搜索,我认为我已经在python中看到了类似的内容,但我不太了解转换为C语言。

我未完成的想法:

void lights()
{
    int delayTime = 0;

    for (int i = 0; /* decrease delayTime by 10% */ )
    {

        light1(on);
        delay(delayTime);
        light1(off);
        delay(delayTime);
        light2(on);
        delay(delayTime);
        light2(off);
        delay(delayTime);

        if (delayTime <= 100)
        {
            // Done end of method/function
        }
    }
}

1 个答案:

答案 0 :(得分:3)

for之后的三个语句是初始化,继续循环的测试条件,以及在每个循环上重复的语句。我们想将delayTime初始化为50,000。如果delayTime大于或等于100,我们希望继续。我们希望将每个循环乘以0.9(最好不要进行任何浮点数学运算)。所以:

for (delayTime = 50000;
    delayTime >= 100;
    delayTime -= delayTime / 10)
{

    light1(on);
    delay(delayTime);
    light1(off);
    delay(delayTime);
    light2(on);
    delay(delayTime);
    light2(off);
    delay(delayTime);
}