目錄
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
參考資料: