复数的四则运算:
(1) 请创建复数运算的项目文件。
(2) 请在项目文件中,创建对复数类的声明文件(.h),在此文件中定义类Complex.
请补充完整Complex类的成员变量和成员函数的声明,具体要求如下:
a) 定义Complex类,该类包含实数类型的实部成员real和虚部成员imag;
b) 定义构造函数,构造函数能够指出无参数实例化,带两个参数实例化,以及实部和虚部都支出默认参数0.0。
c) 定义设置实部的成员函数setreal()。
d) 定义设置虚部的成员函数setimag()。
e) 定义读取实部、读取虚部的函数getreal()、getimag()。
(3) 创建Complex类的实现文件(.cpp),将该类的各成员函数的实现编写在此文件中。
(4) 创建包含复数四则运算的自定义函数的源代码文件(.cpp)。其中包含以下函数
a) 两个复数的加法运算函数。
b) 两个复数的减法运算函数。
c) 两个复数的乘法运算函数。
d) 两个复数的除法运算函数。
(5) 创建测试用的主函数文件(.cpp)。
(6) 调试此程序。
#pragma once
//Complex.h文件
class Complex
{
private:
float imag;
float real;
public:
Complex();
void set(float r, float i);
void get();
Complex add(Complex x);
Complex sub(Complex x);
Complex mul(Complex x);
Complex div(Complex x);
~Complex();
};
//Complex.cpp文件
#include<iostream>
#include"Complex.h"
using namespace std;
void Complex::set(float r = 0, float i = 0)//不传参默认值为零
{
real = r;
imag = i;
}
void Complex::get()
{
if (real != 0)
{
cout << real;
if (imag>0)
cout << "+" << imag << "i";
else if (imag == 0)
cout << imag;
else if (imag<0)
cout << "-" << imag << "i";
}
else
{
if (imag>0)
cout << imag << "i";
else if (imag == 0)
cout << imag;
else if (imag<0)
cout << "-" << imag << "i";
}
cout << endl;
}
Complex Complex::add(Complex x)
{
Complex c;
c.real = real + x.real;
c.imag = imag + x.imag;
return c;
}
Complex Complex::sub(Complex x)
{
Complex c;
c.real = real - x.real;
c.imag = imag - x.imag;
return c;
}
Complex Complex::mul(Complex x)
{
Complex c;
c.real = real*x.real - imag*x.imag;
c.imag = imag + x.real + x.imag*real;
return c;
}
Complex Complex::div(Complex x)
{
Complex c;
if (x.real == 0 && x.imag == 0)
{
cout << "除数不能为零" << endl;
cout << "被除数为:" << endl;
}
else
{
c.real = (real*x.real + imag*x.imag) / (x.real*x.real + x.imag*x.imag);
c.imag = (imag*x.real - x.imag*real) / (x.real*x.real + x.imag*x.imag);
return c;
}
c.real = real + x.real;
c.imag = imag + x.imag;
return c;
}
Complex::Complex()
{
}
Complex::~Complex()
{
}
//主函数测试maintest.cpp文件
#include <iostream>
#include"Complex.h"
using namespace std;
int main()
{
Complex x1, x2, c1, c2, c3, c4;
x1.set(-1, 1);
x2.set(2, 4);
cout << "复数x1的值:" ;
x1.get();
cout << "复数x2的值:";
x2.get();
cout << "x1+x2=";
c1 = x1.add(x2);
c1.get();
cout << "x2-x1=";
c2 = x2.sub(x1);
c2.get();
cout << "x2*x1=";
c3 = x2.mul(x1);
c3.get();
cout << "x2/x1=";
c4 = x2.div(x1);
c4.get();
return 0;
}