2012-12-28 51 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... 
    } 
相关问题