[英]Java Exception Handling for Infinity
我正在尝试编写一个程序,以将任何数字的值等同于任何幂,并且我想对小于零的指数实现异常处理(我成功做到了),并且对值太大而无法输出的异常处理(即无穷。
这是我的幂级,其中包含函数Power:
public class power
{
// instance variables - replace the example below with your own
public static double Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent cannot be less than zero");
}
else if(exp == 0){
return 1;
}
else{
return base * Power(base, exp-1);
}
}
}
这是Test类:
public class powerTest
{
public static void main(String [] args)
{
double [] base = {2.0, 3.0, 2.0, 2.0, 4.0 };
int [] exponent = {10, 9, -8, 6400, 53};
for (int i = 0; i < 5; i++) {
try {
double result = power.Power(base[i], exponent[i]);
System.out.println("result " + result);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
}
这是测试的输出:
result 1024.0
result 19683.0
Exponent cannot be less than zero
result Infinity
result 8.112963841460668E31
我的问题是,如何通过ArithmeticException处理“浮点溢出”方面的内容,使“结果无穷大”表示其他内容?
提前致谢。
当您发现异常时,这里
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
做就是了
System.out.println("Floating point Overflow")
同样(如果您想添加更多内容)或用此语句替换第一张印刷品
就像您说的那样,“您得到结果无穷大”以通过ArithmeticException处理说出其他话”
不确定这是否是您要查找的内容,但是您也可以使用if语句测试无穷大/溢出:
if( mfloat == Float.POSITIVE_INFINITY ){
// handle infinite case, throw exception, etc.
}
因此,根据您的情况,您将执行以下操作:
public static double
Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent less than zero");
}
else if(exp == 0){
return 1;
}
else{
double returnValue = base * Power(base, exp-1);
if(returnValue == Double.POSITIVE_INFINITY)
throw new ArithmeticException("Double overflowed");
return returnValue;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.