learningToCode learningToCode - 3 years ago 36
C Question

Decrease an INT by 10% each round in C

How can I decrease an int (used for my delay time) by 10% each time?
Here is my current concept I would like to improve this.

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);
}


After each lights on/off cycle it can decrease the delay by 10%.
I'm not sure how to go about this I tried googling and I think I've seen something similar in python but I don't understand it enough to convert to C.

My unfinished idea:

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
}
}
}

Answer Source

The three statements after for are the initialization, the test condition for continuing the loop, and the statement repeated on each loop. We want to initialize delayTime to 50,000. We want to continue if delayTime is greater than or equal to 100. And we want to multiply it by 0.9 each loop (preferably without doing any floating point math). So:

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

    light1(on);
    delay(delayTime);
    light1(off);
    delay(delayTime);
    light2(on);
    delay(delayTime);
    light2(off);
    delay(delayTime);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download