2017-05-05 92 views
-2

我必须在代码中显示的特定范围内调整浮点类型剩余计数,这工作正常,但问题是,如果计数是10或20或30,那么会有很多,如果条件,那就是非常低效。如何减少if if语句并使其更好?

下面的示例代码是用于调整高达5计数。

任何建议我该如何改进?

这就是:

for(i = 0; i < 12; i++) 
    { 
    RemainingCount[i] = (((float) CurrentMaterialWeight[i] * (float)TotalMaterialCount[i])/((float) TotalMaterialWeight[i])); 

    if (RemainingCount[i] <= 0.3) 
    { 
     AdjustedRemainingCount[i] = 0; 
    } 

    else if (RemainingCount[i] > 0.50 && RemainingCount[i] <= 1.50) 
    { 
     AdjustedRemainingCount[i] = 1; 
    } 

    else if (RemainingCount[i] > 1.50 && RemainingCount[i] <= 2.50) 
    { 
     AdjustedRemainingCount[i] = 2; 
    } 

    else if (RemainingCount[i] > 2.50 && RemainingCount[i] <= 3.50) 
    { 
      AdjustedRemainingCount[i] = 3; 
    } 

    else if (RemainingCount[i] > 3.50 && RemainingCount[i] <= 4.50) 
    { 
      AdjustedRemainingCount[i] = 4; 
    } 
} 
    So on..... 
+2

为什么你从0.3跳到0.5? – user2357112

+2

颠倒顺序,摆脱'&&'的右边。 –

+0

你不断测试你已经知道的东西。 –

回答

0

舍入应该是诀窍。唯一的问题是您的调整与内置舍入稍有不同,因为您的条件(例如if (..., f <= 1.5))会将值1.5“下拉”为1,而内置舍入round(1.5)会舍入为2

如果你适应你的逻辑,使得1.499999调整为1,但1.5调整为2,比你可以简单地使用int adjustment = round(f)

如果需要完全按照所指定的逻辑,即该1.5调节至1,但1.51调节至2,然后就可以在舍入之前减小浮点值(尽可能少)。因此round(1.5 - epsilon)会给1。 参见下面的代码,这使得使用的内置函数nextafter,其可被用于降低在最小可能步长的浮点值:

#include <math.h> 

int getAdjustment(float f) { 
     return round(nextafter(f, -INFINITY)); 
} 

int main() 
{ 
    float floatValues[9] = {.2,.3,.31,.5,1.5,1.51,2.5,2.51,3.5}; 
    for (int i=0;i<9;i++) { 
     float f = floatValues[i]; 
     cout << f << " adjustment: " << getAdjustment(f) << endl; 
    } 
    return 0; 
} 

输出:

0.2 adjustment: 0 
0.3 adjustment: 0 
0.31 adjustment: 0 
0.5 adjustment: 0 
1.5 adjustment: 1 
1.51 adjustment: 2 
2.5 adjustment: 2 
2.51 adjustment: 3 
3.5 adjustment: 3 
0

我已经给你可以减少IF else语句的代码的逻辑。首先理解逻辑。您可以根据自己的需要修改代码。

int left, right; // declare two integer 

for() 
{ 
RemainingCount[i] = (((float) CurrentMaterialWeight[i] * (float)TotalMaterialCount[i])/((float) TotalMaterialWeight[i])); 

// divide it into two parts RemainingCount[i]= 20.5511; 

char buffer[50]; 
sprintf(buffer, "%lf", value); 
sscanf(buffer, "%d.%d", &left, &right); 
// use what ever way to divide the number 
    // left = 20 right = 5511 

    float leftplus = left + 0.5; 
    float leftminus = left - 0.5; 

    // LEFTplus = 20.5 
    // LEFTminus = 19.5 

    if (your_number <= leftsplus && your_number > leftminus ) 
    { //  20.55 <= 20.5  &&  20.55 > 19.5 
    AdjustedRemainingCount[i] = LEFT; 
    }else{ // 20.55 
      AdjustedRemainingCount[i] = left +1; // 21 
      } 


    }