[英]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.