1.运用java 编写一个复数类,有实部和虚部,并实现复数的加减乘除运算?
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/08 04:40:58
1.运用java 编写一个复数类,有实部和虚部,并实现复数的加减乘除运算?
1.运用java 编写一个复数类,有实部和虚部,并实现复数的加减乘除运算?
1.运用java 编写一个复数类,有实部和虚部,并实现复数的加减乘除运算?
public class ComplexNumber {
\x05/**
\x05 * @param args
\x05 */
\x05int shi,xu;//复数的实部和虚部
\x05public ComplexNumber(int n,int ni){
\x05\x05shi = n;
\x05\x05xu = ni;
\x05}
\x05public void ComplexShow(){
\x05\x05String output = "";
\x05\x05output+=shi;
\x05\x05if(xu>=0){
\x05\x05\x05output+="+";
\x05\x05}
\x05\x05output+=xu;
\x05\x05output+="i";
\x05\x05System.out.println(output);
\x05}
\x05public void ComplexShow1(){//不要换行
\x05\x05String output = "";
\x05\x05output+=shi;
\x05\x05if(xu>=0){
\x05\x05\x05output+="+";
\x05\x05}
\x05\x05output+=xu;
\x05\x05output+="i";
\x05\x05System.out.print(output);
\x05}
\x05public static void ComplexAdd(ComplexNumber x1,ComplexNumber x2){//实现两个复数相加
\x05\x05ComplexNumber cn = new ComplexNumber(0,0);//将两个复数相加等于cn
\x05\x05cn.shi = x1.shi + x2.shi;
\x05\x05cn.xu = x1.xu + x2.xu;
\x05\x05cn.ComplexShow();
\x05}
\x05public static void ComplexMinus(ComplexNumber x1,ComplexNumber x2){//实现两个复数相减,第一个数减第二个数
\x05\x05ComplexNumber cn = new ComplexNumber(0,0);//将两个复数相加等于cn
\x05\x05cn.shi = x1.shi - x2.shi;
\x05\x05cn.xu = x1.xu - x2.xu;
\x05\x05cn.ComplexShow();
\x05}
\x05public static void ComplexMultiply(ComplexNumber x1,ComplexNumber x2){//实现两个复数相乘
\x05\x05ComplexNumber cn = new ComplexNumber(0,0);//将两个复数相加等于cn
\x05\x05cn.shi = x1.shi * x2.shi - x1.xu * x2.xu;
\x05\x05cn.xu = x1.xu * x2.shi + x2.xu * x1.shi;
\x05\x05cn.ComplexShow();
\x05}
\x05public static void ComplexDivide(ComplexNumber x1,ComplexNumber x2){//实现两个复数相除,第一个数除以第二个数
\x05\x05ComplexNumber x2_gong = new ComplexNumber(x2.shi,0-x2.xu);//求被除数的共轭复数
\x05\x05ComplexNumber cn = new ComplexNumber(0,0);//将两个复数相加等于cn
\x05\x05cn.shi = x1.shi * x2_gong.shi - x1.xu * x2_gong.xu;//x1/x2,求分子实部
\x05\x05cn.xu = x1.xu * x2_gong.shi + x2_gong.xu * x1.shi;//x1/x2,求分子虚部
\x05\x05int fenMu = x2.shi * x2.shi + x2.xu * x2.xu;
\x05\x05
\x05\x05if(fenMu!=0){
\x05\x05\x05System.out.print("(");
\x05\x05\x05cn.ComplexShow1();
\x05\x05\x05System.out.print(")");
\x05\x05 System.out.println("/"+fenMu);
\x05\x05}
\x05\x05else
\x05\x05\x05System.out.println("分母为零,无法相除");
\x05\x05\x05
\x05}
\x05public static void main(String[] args) {
\x05\x05// TODO Auto-generated method stub
\x05\x05ComplexNumber cn = new ComplexNumber(-1,-1);//初始化复数
\x05\x05cn.ComplexShow();//显示复数
\x05\x05
\x05\x05ComplexNumber c1 = new ComplexNumber(-1,-1);
\x05\x05ComplexNumber c2 = new ComplexNumber(1,1);
\x05\x05System.out.print("加:");
\x05\x05ComplexAdd(c1,c2);
\x05\x05System.out.print("减:");
\x05\x05ComplexMinus(c1,c2);
\x05\x05System.out.print("乘:");
\x05\x05ComplexMultiply(c1,c2);
\x05\x05System.out.print("除:");
\x05\x05ComplexDivide(c1,c2);//自己化简
\x05}
}