我试图编写一个程序,将任何数字的值等同于任何幂,我应该为指数小于零的指数实现异常处理,这是我成功完成的,也是当值太大而输出不了无穷大时的异常处理。
下面是我的power类,它包含函数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);
}
}
} 下面是测试类:
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处理类似“浮点溢出”的东西来获得“结果无穷大”?
提前谢谢。
发布于 2014-12-07 22:40:57
不确定这是否是您想要的,但是您也可以使用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;
}
}发布于 2014-12-07 22:35:15
当你发现异常的时候,这里
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}就这么做
System.out.println("Floating point Overflow")(如果您想要添加更多),或者用以下语句替换第一个打印
就像你说的那样,“你得到了无限的结果”,通过ArithmeticException处理说出了其他的话“。
https://stackoverflow.com/questions/27348657
复制相似问题