4

我正在尝试比较两个双精度值:

for(int i=0;i<count;i++){
    Double i1=Double.parseDouble(pref.getString("longitude"+i, null));
    Double i2=Double.parseDouble(pref.getString("latitude"+i,null));
    Log.i("Longitude", i1+"");
    Log.i("Latitude",i2+"");
    Log.i("Longitude1",longitude+"");
    Log.i("Latitude1", latitude+"");
    Log.i("note",pref.getString("note"+i, null));


    if(longitude==i1&&latitude==i2) {
        String note=pref.getString("note"+i, null);
        txt.setText(note);
    }
}

共享偏好中有一种组合与经度和纬度相匹配,但是如果我比较它时没有为 textview txt 分配任何值。但是在日志中,纬度和纬度有相同的值。谁能告诉我这有什么问题比较为什么它不执行 txt.settext 语句?

4

4 回答 4

6

我认为存在准确性问题 - 浮点或双炮等类型绝对严格地表示。当我需要比较两个双打时,我会使用这样的东西

double doubleToCompare1 = some double value;
double doubleToCompare2 = another double value;
double EPS = 0.00001;

if(Math.abs(doubleToCompare1-doubleToCompare2)<EPS){
   // assuming doubles are equals
}

EPS 值取决于您需要的准确性。对于坐标,我记得它是逗号后的 6 或 7 符号。

于 2012-12-13T14:54:30.977 回答
5

假设latitude并且longitude也是Double,尝试调用doubleValue两者:

if(longitude.doubleValue() == i1.doubleValue() && latitude.doubleValue() == i2.doubleValue())

或者只是使用equals

if(longitude.equals(i1) && latitude.equals(i2))

它来自第一行,在引擎盖下。

于 2012-12-13T14:43:22.183 回答
1

如果纬度和经度也是Doubles,您需要运行比较equals而不是==

(longitude.equals(i1) && latitude.equals(i2))

如果它们是doubles(即原语),则没有必要,问题出在其他地方。

于 2012-12-13T14:43:35.983 回答
0

只需使用原语而不是类。

for(int i=0;i<count;i++){
    double i1=Double.parseDouble(pref.getString("longitude"+i, null));
    double i2=Double.parseDouble(pref.getString("latitude"+i,null));
    Log.i("Longitude", i1+"");
    Log.i("Latitude",i2+"");
    Log.i("Longitude1",longitude+"");
    Log.i("Latitude1", latitude+"");
    Log.i("note",pref.getString("note"+i, null));


    if(longitude==i1&&latitude==i2) {
        String note=pref.getString("note"+i, null);
        txt.setText(note);
    }
}

我不知道您的经度和纬度变量是什么类型。如果它们是原始(双),则不应做任何事情。如果它们是 Double 对象,请将它们更改为基元,或提取 double 值logitude.doubleValue()

于 2012-12-13T14:54:03.513 回答