2008年4月25日 星期五

JAVA繼承 計算算術平均數與幾何平均數

import java.io.*;
abstract class avg{
protected double first_v;
protected double tal_v;
avg(){
first_v = 1;
}
protected abstract double ans();
public void print_v(double fir_v,double all_v,int mm){
if (mm == 1)
{
for(double i=0; i< all_v; i++)
tal_v = tal_v + ( first_v + i ) ;
}else{
tal_v = 1;
for(double i=0; i< all_v; i++)
tal_v = tal_v * ( first_v + i ) ;
}
System.out.println(tal_v*ans());
}

}

class ma_avg extends avg{
protected double t_v;
ma_avg(){
first_v = 1;
t_v = 1;
}
ma_avg(double to_v){
first_v = 1;
t_v = ((double)(1)/to_v);
}
ma_avg(double fir_v ,double to_v){
first_v = fir_v;
t_v = ((double)(1)/to_v);
}
protected double ans() {
return t_v;
}
}
class th_avg extends avg{
protected double t_v;
th_avg(){
first_v = 1;
t_v = 1;
}
th_avg(double to_v){
first_v = 1;
t_v = Math.sqrt(to_v);
}
th_avg(double fir_v ,double to_v){
first_v = fir_v;
t_v = Math.sqrt(to_v);
}
protected double ans() {
return t_v;
}
}

class work4
{
public static void main(String[] args)
{
avg allavg;
System.out.println("以下為首項為2,項數為2之算術平均數");
allavg= new ma_avg(2,2);
allavg.print_v(2,2,1);
System.out.println("以下為首項為5,項數為2之算術平均數");
allavg= new ma_avg(5,2);
allavg.print_v(5,2,1);
System.out.println("以下為首項為4,項數為4之算術平均數");
allavg= new ma_avg(4,4);
allavg.print_v(4,4,1);
System.out.println("以下為首項為3,項數為6之算術平均數");
allavg= new ma_avg(3,6);
allavg.print_v(3,6,1);
System.out.println("以下為首項為2,項數為2之幾何平均數");
allavg= new th_avg(2,2);
allavg.print_v(2,2,0);
System.out.println("以下為首項為5,項數為2之幾何平均數");
allavg= new th_avg(5,2);
allavg.print_v(5,2,0);
System.out.println("以下為首項為4,項數為4之幾何平均數");
allavg= new th_avg(4,4);
allavg.print_v(4,4,0);
System.out.println("以下為首項為3,項數為6之幾何平均數");
allavg= new th_avg(3,6);
allavg.print_v(3,6,0);
}
}