关于C语言的题目:用结构体定义一个复数,并实现复数的加法、减法和乘法。

2024-11-08 04:52:46
推荐回答(2个)
回答1:

#include   

struct complex  

{  

    int re;  

    int im;  

};  

void add(struct complex a, struct complex  b, struct complex *c)

{

    c->re=a.re+b.re;

    c->im=a.im+b.im;

}

void minus(struct complex a, struct complex  b, struct complex *c)

{

    c->re=a.re-b.re;

    c->im=a.im-b.im;

}

int main()  

{  

    struct complex x,y,s,p;  

    scanf("%d%d",&x.re,&x.im);  

    scanf("%d%d",&y.re,&y.im);  

    add(x,y,&s); 

    printf("   sum=%5d+%5di\n",s.re,s.im);  

    minus(x,y,&p);

    printf("   product=%5d+%5di\n",p.re,p.im);  

}   

扩展资料:

复数运算法则

1、加法交换律:z1+z2=z2+z1

2、乘法交换律:z1×z2=z2×z1

3、加法结合律:(z1+z2)+z3=z1+(z2+z3)

4、乘法结合律:(z1×z2)×z3=z1×(z2×z3)

5、分配律:z1×(z2+z3)=z1×z2+z1×z3

回答2:

#include
#include
typedef struct MyComplex
{
double real;
double img;
}mc;

mc Plus(mc a,mc b)
{
mc result;
result.real = a.real + b.real;
result.img = a.img + b.img;
return result;
}

mc Sub(mc a,mc b)
{
mc result;
result.real = a.real - b.real;
result.img = a.img - b.img;
return result;
}

mc Multi(mc a,mc b)
{
mc result;
result.real = a.real * b.real - a.img * b.img;
result.img = a.img * b.real + b.img * a.real;
return result;
}

void Show(mc a)
{
if(a.real == 0 && a.img == 0)
printf("0.000\n");
else if(a.real == 0)
printf("%.4fi\n",a.img);
else if(a.img == 0)
printf("%.4f\n",a.real);
else
{
if(a.img < 0)
printf("%.4f%.4fi\n",a.real,a.img);
else
printf("%.4f+%.4fi\n",a.real,a.img);
}
}

int main()
{
mc a,b;
printf("输入第一个复数 a:\n");
scanf("%lf%lf",&a.real,&a.img);
printf("输入第二个复数 b:\n");
getchar();
scanf("%lf%lf",&b.real,&b.img);
printf("a b的和: ");
Show(Plus(a,b));
printf("a b的差: ");
Show(Sub(a,b));
printf("a b的积: ");
Show(Multi(a,b));
return 0;
}
按照a+bi这样的格式输入就可以了