For循环而不是long if条件以减少计算时间

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

我有一些如下所示的代码。我已经简化了它,以阐明我的观点。它包含一个数组。在第一部分中,将数组的每个值减去某个值与余量值进行比较。如果满足所有条件,则µC应停止运行简单功能。否则,µC应该使用数组的值进行计算。此计算有针对每个值运行的一些乘法。

uint32_t value[8];
uint16_t othervalue;

if ((value[0] < othervalue && value[1] < othervalue && value[2] < othervalue && value[3] < othervalue && value[4] < othervalue && value[5] < othervalue && value[6] < othervalue && value[7] < othervalue)
{
    othervalue = 100;
    simplefunction();
}
else
{
    calculatewithallvalues(values);
}

我注意到我可能可以改进代码。仅在不满足该特定值的条件的情况下,才需要进行“其他”中的计算。因此,在某些情况下,不必对每个值都进行计算。我想出了使用for循环的另一种方法。但是,这段代码较长,可能更令人困惑。最后需要额外的if循环,以解决所有值均满足条件的可能性。

uint32_t value[8];
uint16_t othervalue;
uint8_t calc_needed = 0;
int i;
for (i=0; i <7; i++)
{
    if (value[i] < othervalue)
    {
        //do nothing
    }
    else
    {
        calculatewithvalue(values[i]);
        calc_needed = 1;
    }
if (calc_needed == 0)
{
    othervalue = 100;
    simplefunction();
}

哪个是更好的解决方案,还是有第三个解决方案?

c loops for-loop microcontroller
1个回答
0
投票

还有第三种解决方案:


for(i=0; i < 7; i++) {
    if (value[i] < othervalue ) continue;
    break;
    }

if (i == 7) { // loop completed; all values were below othervalue
    othervalue = 100;
    simplefunction();
    }
else    {
    calculatewithallvalues(values);
    }
© www.soinside.com 2019 - 2024. All rights reserved.