计算复数 [(8+6i)*(4+3i)]/[(8+6i)+(4+3i)]= ?
复数运算规则详见百度百科
/*
* @Author: jinbo.ma
* @Mail: 18710648068@163.com
* @Date: 2021-03-11 15:02:21
* @LastEditTime: 2021-03-13 16:50:20
*/
#include <stdio.h>
typedef struct complex {
double real, imag;
} complex;
void create (complex *reslut, double real, double imag) {
reslut->real = real;
reslut->imag = imag;
}
void add (complex *reslut, complex a, complex b) {
reslut->real = a.real + b.real;
reslut->imag = a.imag + b.imag;
}
void sub (complex *reslut, complex a, complex b) {
reslut->real = a.real - b.real;
reslut->imag = a.imag - b.imag;
}
void multiply (complex *reslut, complex a, complex b) {
reslut->real = a.real * b.real - a.imag * b.imag;
reslut->imag = a.imag * b.real + a.real * b.imag;
}
int div (complex *reslut, complex a, complex b) {
double tmp = b.real * b.real + b.imag * b.imag;
printf("tmp=%f\n", tmp);
if ( tmp == 0.0 ) {
return -1; //div by zero
}
printf ("%f\n", a.real * b.real + a.imag * b.imag);
printf ("%f\n", a.imag * b.real - a.real * b.imag);
reslut->real = (a.real * b.real + a.imag * b.imag)/tmp;
reslut->imag = (a.imag * b.real - a.real * b.imag)/tmp;
return 0; //success
}
/**
* complex [(8+6i)*(4+3i)]/[(8+6i)+(4+3i)]= ?
* mul=14.000000 + 48.000000i
* sum=12.000000 + 9.000000i
* tmp=225.000000
* 600.000000
* 450.000000
* res=2.666667(或8/3) + 2.000000i
*/
int main (int argc, char **argv) {
complex a, b, mul, sum, res;
create (&a, 8, 6);
create (&b, 4, 3);
multiply (&mul, a, b);
printf ("mul=%f + %fi\n", mul.real, mul.imag);
add (&sum, a, b);
printf ("sum=%f + %fi\n", sum.real, sum.imag);
int ret = div (&res, mul, sum);
if ( ret == -1 ) {
printf ("div by zero!");
} else {
printf ("res=%f + %fi\n", res.real, res.imag);
}
return 0;
}