2012-12-28 44 views
-6

我的代碼中有一個浮點值。比較一個浮點值是否在一個特定的範圍內java/android

我希望使用多個if else語句來檢查它是否在(0,0.5)或(0.5,1)或(1.0,1.5)或(1.5,2.0)範圍內。請爲我提供一個實現這一目標的途徑。

早些時候我想,我可以得到float的確切值。所以,我正在使用下面提到的代碼。但後來我意識到使用==子句來表示浮點變量並不明智。所以,現在我需要檢查變量值是否在特定範圍內。

float ratings=appCur.getFloat(appCur.getColumnIndexOrThrow(DbAdapter.KEY_ROWID)); 


      if(ratings==0){ 
       ivRate.setImageResource(R.drawable.star0); 
      } 
      else if(ratings==0.5){ 
       ivRate.setImageResource(R.drawable.star0_haf); 
      } 
      else if(ratings==1){ 
       ivRate.setImageResource(R.drawable.star1); 
      } 
      else if(ratings==1.5){ 
       ivRate.setImageResource(R.drawable.star1_haf); 
      } 
      else if(ratings==2){ 
       ivRate.setImageResource(R.drawable.star2); 
      } 
+3

[你嘗試過什麼(http://whathaveyoutried.com)? – jlordo

回答

1
float x = ... 
    if (x >= 0.0F && x < 0.5F) { 
     // between 0.0 (inclusive) and 0.5 (exclusive) 
    } else if (x >= 0.5F && x < 1.0F) { 
     // between 0.5 (inclusive) and 1.0 (exclusive) 
    } else if (x >= 1.0F && x < 1.5F) { 
     // between 1.0 (inclusive) and 1.5 (exclusive) 
    } else if (x >= 1.5F && x <= 2.0F) { 
     // between 1.5 (inclusive) and 2.0 (inclusive) 
    } else { 
     // out of range 
    } 
2

以這種方式?

float n; 

...

if (n<0.5f) { // first condition 
    } else if (n<1f) { // second condition 
    } else if (n<1.5f) { // and so on... 
    } 
相關問題