设有复数a=(3,5);b=(4,8);3,4为复数的实部,5,8为复数的虚部.
编程求复数a,b,的加减乘除运算???
----------------解决方案--------------------------------------------------------
等待eastsun的牛代码,新手上路我
[CODE]
/**
*写一个关于复数运算的类
*在java中sqrt(-1)的值为NaN,我们做如下约定:用数组[a,b]代表一个复数,其中
*a代表复数的实部,b代表复数的虚部。
*Complex类实现了复数的基本运算。
*/
import java.util.*;
public final class Complex{
public static double complexNorm(double[] a){
return Math.sqrt(a[0]*a[0]+a[1]*a[1]);
}
public static double[] complexAdd(double[] a,double[] b){
return new double[]{a[0]+b[0],a[1]+b[1]};
}
public static double[] complexSub(double[] a,double[] b){
return new double[]{a[0]-b[0],a[1]-b[1]};
}
public static double[] complexMuti(double[] a,double[] b){
return new double[]{a[0]*b[0]-a[1]*b[1],a[0]*b[1]+a[1]*b[0]};
}
public static double[] complexDvi(double[] a,double[] b){
double c=complexNorm(b)*complexNorm(b);
double[] d={b[0],-b[1]};
double[] e=complexMuti(a,d);
return new double[]{e[0]/c,e[1]/c};
}
public static void main(String[] args){
double[] a={1,2};
double[] b={3,4};
System.out.println(Arrays.toString(complexAdd(a,b)));
System.out.println(Arrays.toString(complexSub(a,b)));
System.out.println(Arrays.toString(complexMuti(a,b)));
System.out.println(Arrays.toString(complexDvi(a,b)));
}
}
----------------解决方案--------------------------------------------------------
* By [url=http://eastsun.javaeye.com]Eastsun[/url]
*/
public class ComplexTest{
public static void main(String[] args){
Complex a =new Complex(1,2);
Complex b =new Complex(2,0);
System.out.println(a+\"+\"+b+\" = \"+a.add(b));
System.out.println(a+\"-\"+b+\" = \"+a.sub(b));
System.out.println(a+\"*\"+b+\" = \"+a.mul(b));
System.out.println(a+\"/\"+b+\" = \"+a.div(b));
}
}
/**
*一个Complex对象,提供add,sub,mul,div方法;并复写了toString方法
*注意,这是一个不可变类;就是说类一旦创建其表示的复数就不会改变
*/
class Complex{
private final double real,image;
public Complex(double r,double i){
real =r;
image =i;
}
/**
*返回一个Complex,代表this+c
*注意,该方法不会改变当前对象的值.其余方法类似
*/
public Complex add(Complex c){
return new Complex(real+c.real,image+c.image);
}
public Complex sub(Complex c){
return new Complex(real-c.real,image-c.image);
}
public Complex mul(Complex c){
return new Complex(real*c.real-image*c.image,real*c.image+image*c.real);
}
public Complex div(Complex c){
double squareL =c.real*c.real+c.image*c.image;
double r =real*c.real -image*c.image;
double i =real*c.image+image*c.real;
return new Complex(r/squareL,i/squareL);
}
public String toString(){
if(image==0) return \"\"+real;
else return \"(\"+real+(image<0?\"\"+image:\"+\"+image)+\"i)\";
}
}
----------------解决方案--------------------------------------------------------
写的都不错,
谢谢了,
值的去好好学习.
----------------解决方案--------------------------------------------------------
请问什么是复数,好像是数学上的问题吧,是我的弱项啊!
----------------解决方案--------------------------------------------------------