繁体   English   中英

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

[英]java incompatible type error else-if statement

我只是试图计算这三个值,但不确定要把什么作为我的else语句。 我放了return,但是它一直在给我一个不兼容的类型错误。 我尝试将其设置为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;
   }  
}

非数字(NaN)拥有一个double类型的值,该值等于Double.longBitsToDouble(0x7ff8000000000000L)返回的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

您的代码

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输入参数是完全未使用的。 您想达到什么目的?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM