编写一个c++程序,实现两个复数相加
2个回答
展开全部
先定义一个复数的类,里面包含复数的表示参数;然后定义一个运算符重载+,用这个+运算符实现两个复数的相加,实体部分 与虚部分分别计算
#include<iostream.h>
class Complex
{
private:
float Realpart;
float Imagepart;
public:
Complex::Complex(float r,float i) {Realpart=r; Imagepart=i;}
static void print(const Complex c1); const Complex operator+(const Complex& c1);//使用成员函数重载加号运算符
};
const Complex Complex::operator+(const Complex& c1)
{
Complex c(0,0);
c.Imagepart = Imagepart + c1.Imagepart;
c.Realpart = Realpart + c1.Realpart;
return c;
}
void Complex::print(const Complex c)
{
cout<<c.Realpart<< " "<<c.Imagepart<<endl;
}
void main()
{
Complex a(2,4);
Complex b(1,3);
Complex c(0,0);
c = a + b;
c.print(c);
}
#include<iostream.h>
class Complex
{
private:
float Realpart;
float Imagepart;
public:
Complex::Complex(float r,float i) {Realpart=r; Imagepart=i;}
static void print(const Complex c1); const Complex operator+(const Complex& c1);//使用成员函数重载加号运算符
};
const Complex Complex::operator+(const Complex& c1)
{
Complex c(0,0);
c.Imagepart = Imagepart + c1.Imagepart;
c.Realpart = Realpart + c1.Realpart;
return c;
}
void Complex::print(const Complex c)
{
cout<<c.Realpart<< " "<<c.Imagepart<<endl;
}
void main()
{
Complex a(2,4);
Complex b(1,3);
Complex c(0,0);
c = a + b;
c.print(c);
}
展开全部
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double real = 0.0,double image = 0.0)
{
m_real = real; m_image = image;
}
Complex operator+(const Complex &c)
{
return Complex(this->m_real + c.m_real,this->m_image + c.m_image);
}
friend ostream &operator<<(ostream &os , const Complex &c)
{
os << c.m_real << " + " << c.m_image << "i";
return os;
}
void print(Complex &c);
private:
double m_real;
double m_image;
};
int main()
{
Complex a(1,2);
Complex b(3,4);
Complex c = a + b;
cout << c <<endl;
return 0;
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询