复数的加减乘除
这是出自某学习网站的一道题,主要是本人写的,结尾部分为自带部分。
*// 复数加法
COMPLEX ComplexAdd(const COMPLEX *x, const COMPLEX *y);
// 复数减法
COMPLEX ComplexSub(const COMPLEX *x, const COMPLEX *y);
// 复数乘法
COMPLEX ComplexMul(const COMPLEX *x, const COMPLEX *y);
// 复数除法
COMPLEX ComplexDiv(const COMPLEX *x, const COMPLEX y);
//为除数,y为被除数
要求:当除数为零时,ComplexDiv 函数报告错误,函数值为零。
*示例 1
输入
4.2+1.5i
2.5-0.3i
输出
6.7+1.2i
1.7+1.8i
10.95+2.49i
1.58517+0.790221i
#include <stdio.h>
typedef struct complex
{
double re;
double im;
}COMPLEX;
void ComplexInput(COMPLEX *complex){
scanf("%lf%lfi",&complex->re,&complex->im);
}
void ComplexOutput(const COMPLEX *complex){
printf("%g%+gi",complex->re,complex->im);
}
// 复数加法
COMPLEX ComplexAdd(const COMPLEX *x, const COMPLEX *y)
{
COMPLEX p;
p.re = x->re + y->re;
p.im = x->im + y->im;
return p;
}
// 复数减法
COMPLEX ComplexSub(const COMPLEX *x, const COMPLEX *y)
{
COMPLEX q;
q.re = x->re - y->re;
q.im = x->im - y->im;
return q;
}
// 复数乘法
COMPLEX ComplexMul(const COMPLEX *x, const COMPLEX *y)
{
COMPLEX r;
r.re = (x->re * y->re)-(x->im * y->im);
r.im = (x->re * y->im)+(x->im * y->re);
return r;
}
// 复数除法
COMPLEX ComplexDiv(const COMPLEX *x, const COMPLEX *y)
{
COMPLEX s;
if(y->re!=0&&y->im!=0)
{ double w=(y->re * y->re + y->im * y->im);
s.re = ((x->re * y->re)+(x->im * y->im))/w;
s.im = -((x->re * y->im)-(x->im * y->re))/w;}
if(y->re==0&&y->im==0)
{printf("Divided by zero!\n");
return *y;}
return s;
}
int main()
{
COMPLEX a, b, p, q, r, s;
ComplexInput(&a);
ComplexInput(&b);
p = ComplexAdd(&a, &b);
ComplexOutput(&p);
putchar('\n');
q = ComplexSub(&a, &b);
ComplexOutput(&q);
putchar('\n');
r = ComplexMul(&a, &b);
ComplexOutput(&r);
putchar('\n');
s = ComplexDiv(&a,&b);
ComplexOutput(&s);
putchar('\n');
return 0;
}
p, q, r, s分别作为复数加减乘除运算结果输出
我也是刚开始学C语言,写的不好,勿喷,谢谢