C语言复数运算(结构体)

复数的加减乘除

这是出自某学习网站的一道题,主要是本人写的,结尾部分为自带部分。
*// 复数加法
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语言,写的不好,勿喷,谢谢

  • 23
    点赞
  • 103
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值