编程实现两个复数的运算。设有两个复数 和 ,则他们的运算公式为:
要求:(1)定义一个结构体类型来描述复数。
(2)复数之间的加法、减法、乘法和除法分别用不用的函数来实现。
(3)必须使用结构体指针的方法把函数的计算结果返回。
说明:用户输入:运算符号(+,-,*,/) a b c d.
输出:a+bi,输出时不管a,b是小于0或等于0都按该格式输出,输出时a,b都保留两位。
输入:
- 2.5 3.6 1.5 4.9
输出:
1.00+-1.30i
import java.util.*; public class Main { private Scanner scanner; public static void main(String[] args) { new Main(); } private Main(){ scanner = new Scanner(System.in); solve(); } private void solve(){ char op = scanner.next().charAt(0); double a = scanner.nextDouble(); double b = scanner.nextDouble(); double c = scanner.nextDouble(); double d = scanner.nextDouble(); Complex complex = new Complex(a,b); if(op == '+'){ complex.add(new Complex(c,d)); } else if(op == '-'){ complex.sub(new Complex(c,d)); } else if(op == '*'){ complex.mul(new Complex(c,d)); } else if (op == '/'){ complex.div(new Complex(c,d)); } complex.print(); } } class Complex{ private double a; private double b; public Complex(double a,double b){ this.a = a; this.b = b; } public void add(Complex complex){ a += complex.a; b += complex.b; } public void sub(Complex complex){ a -= complex.a; b -= complex.b; } public void mul(Complex complex){ double c = complex.a; double d = complex.b; double temp = a; a = a*c-b*d; b = temp*d+b*c; } public void div(Complex complex){ double c = complex.a; double d = complex.b; double temp = a; a = (a*c+b*d)/(c*c+d*d); b = (b*c-temp*d)/(c*c+d*d); } public void print(){ System.out.printf("%.2f",a); System.out.print("+"); System.out.printf("%.2f",b); System.out.println("i"); } }