2017-05-05 66 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 
      } 


    }