1樓
大 中
小 發表於 2006-8-7 20:35
[JAVA] 利用繼承來擴充階乘的運算
引用:import java.io.*;
//這只是一個標準的階乘計算class
class frac{
static int y;
public static int fraction() //算階乘
{ int ans,i;
ans=1;
for (i=1;i<=y;i=i+1) ans=ans*i;
return(ans);
} // fraction 結束
}
//這個class用來擴充階乘的計算,讓實數也可以被計算
public class demo24 extends frac {
//實數階乘,這個就是擴充的方法
private static int relfraction(double yy)
{ int ans;
int newy,i;
newy=(int) yy; //換成整數
System.out.println("哪有人輸入實數的,下次請輸入整數:"+newy);
ans=1;
for (i=1;i<=newy;i=i+1) ans=ans*i;
return(ans);
} // fraction 結束
//程式進入點
public static void main(String args[]) throws Exception
{ //程式進入點
String getbr;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int x,pt;
double fx;
/*****請使用者輸入選項**********/
x=5;
demo24 target=new demo24(); //將 demo24 物件實體化
while (x>=0)
{
System.out.print("請輸入要計算階乘的數字:");
getbr = br.readLine();
/*****判斷是否是整數*******/
pt=getbr.indexOf("."); //輸入字串如果有小數點就是實數
if (pt < 0) //整數
{
x=Integer.parseInt(getbr);
if (x<0)
{
System.out.println("謝謝!再見!");
continue;
}
target.y=x;
System.out.println(x+ "!="+target.fraction());
}
else
{
fx=Double.parseDouble(getbr);
if (fx<0)
{
System.out.println("謝謝!再見!");
continue;
}
System.out.println(fx+ "!="+target.relfraction(fx));
}
} //while結束
} //main 結束
}
|