抽象数据类型(复数四则运算实现)
Posted yangbocsu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了抽象数据类型(复数四则运算实现)相关的知识,希望对你有一定的参考价值。
抽象数据类型(复数四则运算实现)
void multiply(Complex *C, Complex A,Complex B)//A*B
{
C -> realpart = A.realpart * B.realpart - A.imagpart*B.imagpart;
C -> imagpart = A.imagpart*B.realpart + A.realpart*B.imagpart;
}
void divide(Complex *C, Complex A,Complex B)//A/B
{
C -> realpart = (A.realpart * B.realpart + A.imagpart*B.imagpart)/(B.realpart*B.realpart + B.imagpart*B.imagpart);
C -> imagpart = (A.imagpart*B.realpart - A.realpart*B.imagpart)/(B.realpart*B.realpart + B.imagpart*B.imagpart);
}
【完整实现代码】
// By yangbocsu 2021.07.08 民主楼
#include <stdio.h>
typedef struct
{
float realpart;
float imagpart;
} Complex;
void assign(Complex *A, float real,float imag);//赋值
void add(Complex *C, Complex A,Complex B);//A+B
void minu(Complex *C, Complex A,Complex B);//A-B
void multiply(Complex *C, Complex A,Complex B);//A*B
void divide(Complex *C, Complex A,Complex B);//A/B
int main(int argc, char const *argv[])
{
Complex z1,z2,z3,z4,z5,z6;
assign(&z1,8.0,6.0);
assign(&z2,4.0,3.0);
// assign(&z1,1.0,2.0);
// assign(&z2,2.0,-3.0);
add(&z3,z1,z2);
minu(&z4,z1,z2);
multiply(&z5,z1,z2);
divide(&z6,z1,z2);
printf("z1 = %f+%fi\\n",z1.realpart,z1.imagpart);
printf("z2 = %f+%fi\\n",z2.realpart,z2.imagpart);
printf("z1 + z2 = %f+%fi\\n",z3.realpart,z3.imagpart);
printf("z1 - z2 = %f+%fi\\n",z4.realpart,z4.imagpart);
printf("z1 * z2 = %f+%fi\\n",z5.realpart,z5.imagpart);
printf("z1 / z2 = %f+%fi\\n",z6.realpart,z6.imagpart);
return 0;
}
void assign(Complex *A, float real,float imag)//赋值
{
A -> realpart = real;
A -> imagpart = imag;
}
void add(Complex *C, Complex A,Complex B)//A+B
{
C -> realpart = A.realpart + B.realpart;
C -> imagpart = A.imagpart + B.imagpart;
}
void minu(Complex *C, Complex A,Complex B)//A+B
{
C -> realpart = A.realpart - B.realpart;
C -> imagpart = A.imagpart - B.imagpart;
}
void multiply(Complex *C, Complex A,Complex B)//A*B
{
C -> realpart = A.realpart * B.realpart - A.imagpart*B.imagpart;
C -> imagpart = A.imagpart*B.realpart + A.realpart*B.imagpart;
}
void divide(Complex *C, Complex A,Complex B)//A/B
{
C -> realpart = (A.realpart * B.realpart + A.imagpart*B.imagpart)/(B.realpart*B.realpart + B.imagpart*B.imagpart);
C -> imagpart = (A.imagpart*B.realpart - A.realpart*B.imagpart)/(B.realpart*B.realpart + B.imagpart*B.imagpart);
}
以上是关于抽象数据类型(复数四则运算实现)的主要内容,如果未能解决你的问题,请参考以下文章