数据结构,,,复数的表示及加减运算

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <map>
#include <string.h>
#include <queue>
const int N = 0x3f3f3f;

using namespace std;

typedef struct
{
    float Realpart;//实部
    float Imagepart;//虚部
}Complex;

void Create(Complex &C,float x,float y)
{
    C.Realpart=x;//获得实部
    C.Imagepart=y;//获得虚部
}

float GetReal(Complex C)
{
    return C.Realpart;//获得实部
}

float GetImag(Complex C)
{
    return C.Imagepart;//获得虚部
}

Complex Add(Complex C1,Complex C2)//复数加法
{
    Complex sum;
    sum.Realpart=C1.Realpart+C2.Realpart;
    sum.Imagepart=C1.Imagepart+C2.Imagepart;
    return sum;
}

Complex Sub(Complex C1,Complex C2)//复数减法
{
    Complex difference;
    difference.Realpart=C1.Realpart-C2.Realpart;
    difference.Imagepart=C1.Imagepart-C2.Imagepart;
    return difference;
}

int main()
{
Complex C1,C2,C3,C4,C5;
float x1,x2,y1,y2;

printf("
复数是由实部和虚部组成的数,通常表示为 a + bi 的形式,其中 a 是实部,b 是虚部,i 是虚数单位,满足 i^2 = -1。在数据结构中,复数加减除运算通常可以通过定义复数数据结构实现相应的操作函数完成。以下是一个简单的实现示例: 首先,我们定义一个复数的类,并实现构造函数以及加减乘除的方法: ```python class Complex: def __init__(self, real, imag): self.real = real self.imag = imag def __add__(self, other): return Complex(self.real + other.real, self.imag + other.imag) def __sub__(self, other): return Complex(self.real - other.real, self.imag - other.imag) def __mul__(self, other): new_real = self.real * other.real - self.imag * other.imag new_imag = self.real * other.imag + self.imag * other.real return Complex(new_real, new_imag) def __truediv__(self, other): denominator = other.real ** 2 + other.imag ** 2 new_real = (self.real * other.real + self.imag * other.imag) / denominator new_imag = (self.imag * other.real - self.real * other.imag) / denominator return Complex(new_real, new_imag) def __str__(self): return f"{self.real} + {self.imag}i" # 使用示例 c1 = Complex(1, 2) c2 = Complex(3, 4) print("c1 + c2 =", c1 + c2) print("c1 - c2 =", c1 - c2) print("c1 * c2 =", c1 * c2) print("c1 / c2 =", c1 / c2) ``` 在上述代码中,`Complex` 类定义了复数的基本结构和操作。`__add__`、`__sub__`、`__mul__` 和 `__truediv__` 分别重载了、乘、除运算符,以便可以直接使用这些运算符进行复数运算。`__str__` 方法用于提供复数的字符串表示形式。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>