Java实现复数运算

时间:2023-03-10 03:31:20
Java实现复数运算

1 问题描述

编程实现两个复数的运算。设有两个复数 和 ,则他们的运算公式为:

要求:(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

2 解决方案

package com.liuzhen.systemExe;

import java.io.IOException;
import java.util.Scanner; public class Main{ public void complexOperation(char operation,double a,double b,double c,double d){
if(operation == '+'){
double temp1 = a + c;
double temp2 = b + d;
System.out.printf("%.2f",temp1);
System.out.print("+");
System.out.printf("%.2f",temp2);
System.out.print("i");
} if(operation == '-'){
double temp1 = a - c;
double temp2 = b - d;
System.out.printf("%.2f",temp1);
System.out.print("+");
System.out.printf("%.2f",temp2);
System.out.print("i");
} if(operation == '*'){
double temp1 = a*c - b*d;
double temp2 = a*d + b*c;
System.out.printf("%.2f",temp1);
System.out.print("+");
System.out.printf("%.2f",temp2);
System.out.print("i");
} if(operation == '/'){
double temp1 = (a*c + b*d)/(c*c + d*d);
double temp2 = (b*c - a*d)/(c*c + d*d);
System.out.printf("%.2f",temp1);
System.out.print("+");
System.out.printf("%.2f",temp2);
System.out.print("i");
}
} public static void main(String[] args){
Main test = new Main();
Scanner in = new Scanner(System.in);
//System.out.println("请输入一个运算符和四个数字:");
//此处重点在于单个字符的输入问题
char operation = 0;
try {
operation = (char)System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
double[] temp = new double[4];
for(int i = 0;i < 4;i++){
temp[i] = in.nextDouble();
}
test.complexOperation(operation, temp[0], temp[1], temp[2], temp[3]);
}
}

运行结果:

请输入一个运算符和四个数字:
+ 1 2 3 4
4.00+6.00i 请输入一个运算符和四个数字:
- 1 2 3 4
-2.00+-2.00i