English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

麻煩大家..因為java初學..想要請問下面幾個問題來參考=\"=感謝..

1.請撰寫一個類別Complex,代表複數,並為其定義複數加減運算的方法。

2.請撰寫一個類別Circle,代表一個圓,並提供多種建構方法可以透過指定圓心座標及半徑或是一個包含此圓的最小正方形來建立Circle物件,同時定義方法可以計算圓週及圓面積。

3.請撰寫一個類別Calculator,利用static方法提供計算次方、階乘等方法。

2006-06-18 04:35:04 · 1 個解答 · 發問者 Anonymous in 電腦與網際網路 程式設計

1 個解答

1.請撰寫一個類別Complex,代表複數,並為其定義複數加減運算的方法。
public class Complex{
private double r, c;
public Complex(double ir, double ic){
r=ir;
c=ic;
}
public Complex add(Complex a){
Complex result = new Complex(0,0);
result.r=r+a.r;
result.c=c+a.c;
return result;
}
public Complex sub(Complex a){
Complex result = new Complex(0,0);
result.r=r-a.r;
result.c=c- a.c;
return result;
}
public double r(){return r;}
public double c(){return c;}
public static void main(String args[]){
Complex a = new Complex(1,2);
Complex b = new Complex(3,4);
Complex c = a.add(b);
System.out.println("real: " + c.r() + ", complex: " + c.c());
c = a.sub(b);
System.out.println("real: " + c.r() + ", complex: " + c.c());
}
};
2.請撰寫一個類別Circle,代表一個圓,並提供多種建構方法可以透過指定圓心座標及半徑或是一個包含此圓的最小正方形來建立Circle物件,同時定義方法可以計算圓週及圓面積。
public class Square{
public double x1, y1, x2, y2;
public Square(double x1, double y1, double x2, double y2){
this.x1 = x1;
this.y2 = y1;
this.x2 = x2;
this.y2 = y2;
}
}
public class Circle{
private double x, y, r;
public Circle(double x, double y, double r)
{
this.x = x;
this.y = y;
this.r = r;
}
public Circle(Square s){
x = (s.x1+s.x2)/2;
y = (s.y1+s.y2)/2;
r = (s.x2-s.x1)/2;
}
double circumference(){return 2*java.lang.Math.PI*r;}
double area(){return r*r*java.lang.Math.PI;}
public static void main(String args[]){
Circle c1 = new Circle(0, 0, 10);
System.out.println("circumferernce: "+c1.circumference());
System.out.println("area: "+c1.area());
Square s = new Square(0, 0, 2, 2);
Circle c2 = new Circle(s);
System.out.println("circumferernce: "+c2.circumference());
System.out.println("area: "+c2.area());
}
}
3.請撰寫一個類別Calculator,利用static方法提供計算次方、階乘等方法。
public class Calculator{
static double power(double x, int y){
boolean invert;
if (y < 0){
y = -y;
invert = true;
}
else
invert = false;
double result = 1;
for(int i=0; i result *= x;
if(invert)
result = 1/result;
return result;
}
static int factorial(int x){
int result = 1;
while(x > 1)
result *= x--;
return result;
}
public static void main(String argv[]){
System.out.println("power(2,3)="+Calculator.power(2,3));
System.out.println("factorial(5)="+Calculator.factorial(5));
}
}

2006-06-19 04:28:15 · answer #1 · answered by Code Monkey 4 · 0 0

fedest.com, questions and answers