欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c++用结构和类编程分别实现复数加法和乘法

程序员文章站 2022-12-11 07:59:02
问题描述:分别使用结构和类编程实现复数加减法 /*使用复数结构,编写通用函数求两个复数的和和积*/ struct complex { int real;...

问题描述:分别使用结构和类编程实现复数加减法

/*使用复数结构,编写通用函数求两个复数的和和积*/
struct complex
{
    int real;
    int im;
};

struct complex cadd(struct complex c1,struct complex c2);
struct complex cadd(struct complex c1,struct complex c2) 
//现在cadd是一个返回类型是struct complex的函数
{
    struct complex result;
    result.real=c1.real+c2.real;
    result.im=c1.im+c2.im;
    return result;

}

struct complex cmult(struct complex c1, struct complex c2);

struct complex cmult(struct complex c1, struct complex c2)
{
    struct complex result;
    result.real = c1.real*c2.real - c1.im*c2.im;
    result.im = c1.real*c2.im + c1.im*c2.real;
    return result;
}

//编写结果输出函数
void puts(struct complex c);
void puts(struct complex c)
{
    cout<>c1.real&&cin>>c1.im&&cin>>c2.real&&cin>>c2.im)
    {
        c3=cadd(c1,c2);
        puts(c3);
        c3=cmult(c1,c2);
        puts(c3);
    }
    cin.get();
}
/*用类来实现复数的加法和乘法*/

class complex
{
public:
    int real;
    int im;
//   complex(int m=0,int n=0);

    void set_c(int m,int n);
    void cadd(complex c1, complex c2);
    void cmult(complex c1,complex c2);
    void put();
};

//complex::complex(int m,int n)
//{
//  real = m;
//  im = n;
//}

void complex::set_c(int m, int n)
{
    real = m; 
    im = n;
}
void complex::cadd(complex c1, complex c2)
{
    real = c1.real + c2.real;
    im = c1.im + c2.im;
}

void complex::cmult(complex c1,complex c2)
{   
    real = c1.real*c2.real - c1.im*c2.im;
    im = c1.real *c2.im + c2.real*c1.im;
}
void complex::put()
{
    cout<>r1 && cin>>i1 &&cin>>r2 &&cin>>i2)
    {
        c1.set_c(r1,i1);
        c1.put();
        c2.set_c(r2,i2);
        c2.put();
        c3.cadd(c1,c2);
        c3.put();
        c3.cmult(c1,c2);
        c3.put();
    }
    cin.get();
}