复数的求和

一、什么是复数

我们都知道实数,例如1,-7,3.25,其实复数就是比实数范围更广的数。因为表达式x * x + 1= 0无法解出x的值,所以引入i来表示,定义i的平方等于-1;所以i * i  = -1,x * x = i * i。

复数形如z = a+bi;(a和b为实数,i是固定不变的字母,只有i的平方有数值为-1)

b等于0时z = a为实数;b不等于0时,z = a + bi为虚数;虚数中a 等于0时z = bi为纯虚数。

二、复数的求和

例如:z1 = -5 + 2i;z2 = 10.5 + 0.15i;       相加结果为z = 5.50 + 2.15i

简单代码

typedef struct
{   
    float x;
    float y;
}cpl;
void add(cpl num1,cpl num2)
{   
    float sum1, sum2;
    sum1 = num1.x + num2.x;
    sum2 = num1.y + num2.y;
    printf("两个复数相加为z=%.2f+%.2fi\r\n",sum1,sum2);
}
int main()
{
    cpl num1,num2;
    printf("请输入第一个复数:\r\n");
    scanf("%f%f",&num1.x,&num1.y);
    printf("请输入第二个复数:\r\n");
    scanf("%f%f",&num2.x,&num2.y);
    add(num1,num2);
}

输出结果为

请输入第一个复数:
-5 2
请输入第二个复数:
10.5 0.15
两个复数相加为z=5.50+2.15i

下面是一个实现复数求和运算的 Java 代码,包含了两个复数数、复数数组的求和运算方法: ```java public class ComplexNumber { private double real; private double imaginary; public ComplexNumber(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } public ComplexNumber add(ComplexNumber other) { double resultReal = this.real + other.real; double resultImaginary = this.imaginary + other.imaginary; return new ComplexNumber(resultReal, resultImaginary); } public static ComplexNumber sum(ComplexNumber[] numbers) { double sumReal = 0; double sumImaginary = 0; for (ComplexNumber number : numbers) { sumReal += number.real; sumImaginary += number.imaginary; } return new ComplexNumber(sumReal, sumImaginary); } public String toString() { String sign = this.imaginary < 0 ? "-" : "+"; return String.format("%.2f %s %.2fi", this.real, sign, Math.abs(this.imaginary)); } } ``` 这里定义了一个 `ComplexNumber` 类,表示复数,包含了实部和虚部两个属性,并提供了复数加法的实例方法 `add()` 和复数数组求和的静态方法 `sum()`。在 `toString()` 方法中,定义了复数的字符串表示方式,方便输出结果。 下面是一个示例代码,展示了如何使用这个类进行复数求和运算: ```java public class Test { public static void main(String[] args) { ComplexNumber c1 = new ComplexNumber(3, 4); ComplexNumber c2 = new ComplexNumber(2, -1); ComplexNumber c3 = new ComplexNumber(-1, 2); ComplexNumber[] numbers = {c1, c2, c3}; ComplexNumber sum1 = c1.add(c2); // 复数加法 ComplexNumber sum2 = ComplexNumber.sum(numbers); // 复数数组求和 System.out.println("c1 = " + c1); System.out.println("c2 = " + c2); System.out.println("c3 = " + c3); System.out.println("c1 + c2 = " + sum1); System.out.println("sum = " + sum2); } } ``` 运行结果如下: ``` c1 = 3.00 + 4.00i c2 = 2.00 - 1.00i c3 = -1.00 + 2.00i c1 + c2 = 5.00 + 3.00i sum = 4.00 + 5.00i ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值