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



我只是试图计算这三个值,而不确定要将什么作为我的其他语句。我放了返回,但它只是给我一个不兼容的类型错误。我尝试将其设置为空,而NAN则指出,我不能这样做,而类型是双重的。任何帮助都将不胜感激。

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

not-a-number(nan)具有double类型的值,该值等同于Double.longBitsToDouble(0x7ff8000000000000L)返回的值AS: -

public static final double NaN = 0.0d / 0.0;

因为在您的情况下,您使用的是 oprive type 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

您的代码

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输入参数简直是未使用的。您想实现什么?

最新更新