java不兼容类型错误else-if语句

时间:2017-10-02 02:37:21

标签: java if-statement return incompatibletypeerror

我只是试图计算这三个值而不确定将什么作为我的else语句。我把返回,但它只是一直给我一个不兼容的类型错误。我已经尝试将其设置为null,并且NaN但它声明我不能这样做,类型为double。任何帮助表示赞赏。

public static double getE(int i) {
    double e = 1, x=1;
    for(i = 1; i <= 100000; i++){
        x=x/i;
        if (i == 10000) {
            return x;
        }
        else if (i == 20000) {
            return x;
        }
        else if (i == 100000) {
            return x;
        } 
        return;
   }  
}

2 个答案:

答案 0 :(得分:0)

非数字(NaN)包含double类型的值,该值等同于Double.longBitsToDouble(0x7ff8000000000000L)返回的值: -

public static final double NaN = 0.0d / 0.0;

因为在你的情况下,你使用的是原语类型double (它只是数据而不是对象,因此也不能是null),你可以通过将return更改为

来直接使用这些值
return 0.0d;

并确保它在for循环之外

for (i = 1; i <= 100000; i++) {
    x = x / i;
    if (i == 10000) {
        return x;
    } else if (i == 20000) {
        return x;
    } else if (i == 100000) {
        return x;
    }
}
return 0.0d; // default value, in case the for loop wasn't executed

答案 1 :(得分:0)

你的代码

public static double getE(int i) {
    double e = 1, x=1;
    for(i = 1; i <= 100000; i++){
        x=x/i;
        if (i == 10000) {
            return x;
        }
        else if (i == 20000) {
            return x;
        }
        else if (i == 100000) {
            return x;
        } 
        return;
   }  
}

严格等同于

public static double getE(int i) {
   return;
}

并且i输入参数未使用。 你想要实现什么目标?

相关问题