复数,由实部和虚部构成。 用Java编写完整程序,实现以下功能: 从键盘输入两个复数,分别记作a和b 计算a+b,a-b,a*b,并输出考虑类的设计,根据需要设计类,要求至少两个类 一个是主类,负责调用(或组装); 另一个是功能类,实现题目的主体功能要求。只使用Scanner
时间: 2024-06-15 08:04:34 浏览: 171
复数是由实部和虚部构成的数,可以表示为a+bi的形式,其中a为实部,b为虚部,i为虚数单位。
以下是一个使用Java编写的程序,实现从键盘输入两个复数,计算它们的和、差和积,并输出结果。程序中使用了Scanner类来获取用户输入。
```java
import java.util.Scanner;
class Complex {
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex add(Complex other) {
double realSum = this.real + other.real;
double imaginarySum = this.imaginary + other.imaginary;
return new Complex(realSum, imaginarySum);
}
public Complex subtract(Complex other) {
double realDiff = this.real - other.real;
double imaginaryDiff = this.imaginary - other.imaginary;
return new Complex(realDiff, imaginaryDiff);
}
public Complex multiply(Complex other) {
double realProduct = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryProduct = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(realProduct, imaginaryProduct);
}
@Override
public String toString() {
return real + " + " + imaginary + "i";
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个复数的实部:");
double real1 = scanner.nextDouble();
System.out.println("请输入第一个复数的虚部:");
double imaginary1 = scanner.nextDouble();
Complex a = new Complex(real1, imaginary1);
System.out.println("请输入第二个复数的实部:");
double real2 = scanner.nextDouble();
System.out.println("请输入第二个复数的虚部:");
double imaginary2 = scanner.nextDouble();
Complex b = new Complex(real2, imaginary2);
Complex sum = a.add(b);
Complex difference = a.subtract(b);
Complex product = a.multiply(b);
System.out.println("两个复数的和为:" + sum);
System.out.println("两个复数的差为:" + difference);
System.out.println("两个复数的积为:" + product);
}
}
```
阅读全文