-6

我的代码中有一个浮点值。

我希望使用多个 if else 语句来检查它是否在 (0,0.5) 或 (0.5,1) 或 (1.0,1.5) 或 (1.5,2.0) 范围内。请建议我实现这一目标的方法。

早些时候我想,我可以得到浮点数的确切值。所以,我正在使用下面提到的代码。但后来我意识到对浮点变量使用 == 子句是不明智的。所以,现在我需要检查变量值是否在特定范围内。

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);
            }
4

2 回答 2

2

这样?

  float n;

...

  if (n<0.5f)  {  // first condition
  } else if (n<1f) { // second condition
  } else if (n<1.5f) { // and so on...
  }
于 2012-12-28T11:42:48.643 回答
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
    }
于 2012-12-28T11:45:48.833 回答