实验5小型特殊计算器设计
一,实验内容:
使用面向对象的程序设计方法设计一个程序,实现对标准类型数据和复数类型数据进行加、减、乘、除的运算。
二,实验要求:
①程序要有总菜单:即至少要有标准类型数据计算、复数类型数据计算和退出选项;
②复数类型数据计算要通过运算符重载函数实现;
③在输入、输出复数时用到的插入、提取流运算符也要重载;
④设计的程序代码要精练。
#include<iostream>
using namespace std;
class complex
{
public:
double f;
double s;
complex()
{
f = 0;
s = 0;
}
//复数加法
complex operator + (complex b)
{
complex c;
c.f = f + b.f;
c.s = s + b.s;
return c;
}
//复数减法
complex operator - (complex b)
{
complex c;
c.f = f - b.f;
c.s = s - b.s;
return c;
}
//复数乘法
complex operator * (complex b)
{
complex c;
c.f = (f * b.f) - s * b.s;
c.s = s * b.f + (f * b.s);
return c;
}
//复数除法
complex operator / (complex b)
{
complex c;
c.f = f * b.f + s * b.s/(b.f * b.f + b.s * b.s);
c.s = (s * b.f + f * b.s)/(b.f * b.f + b.s * b.s);
return c;
}
//输出运算符重载
friend ostream& operator << (ostream& co,complex& a)
{
if(a.s > 0)
co<<a.f<<"+"<<a.s<<"i"<<endl;
else if(a.s == 0)
co<<a.f<<endl;
else
co<<a.f<<a.s<<"i"<<endl;
return co;
}
//输入运算符重载
friend istream& operator >> (istream& ci,complex& a)
{
ci>>a.f>>a.s;
return ci;
}
};
void welcome ()
{
cout<<" $--------------------------------------------$"<<endl;
cout<<" : :"<<endl;
cout<<" : **欢迎进入计算器** : "<<endl;
cout<<" : by:贾岱华 :"<<endl;
cout<<" $--------------------------------------------$"<<endl;
return;
}
int welcome1()
{
int r = 0,loop = 1;
cout<<endl<<"1: 标准类型计算"<<endl;
cout<<"2: 复数型计算"<<endl;
cout<<"0: 退出"<<endl;
while(loop)
{
cin>>r;
if(r <= 2 && r >= 0)
return r;
}
return r;
}
int main()
{
complex a,b,c;
char e;
double x = 0,y = 0,z = 0;
int lo = 1,r;
welcome();
while(lo)
{
r = welcome1();
if(r == 0)
break;
else if(r == 1)
{
cout<<"请输入计算的值:" ;
cin>>x;
cout<<"请输入计算的值:" ;
cin>>y;
cout<<"请输入运算类型:" ;
cin>>e;
if(e == '+')
cout<<x+y<<endl;
else if(e == '-')
cout<<x-y<<endl;
else if(e == '*')
cout<<x * y<<endl;
else if(e == '/')
cout<<x / y<<endl;
}
else if(r == 2)
{
cout<<"请输入复数(样例:复数为1+4i,则输入1 4):" ;
cin>>a;
cout<<"请输入复数(样例:复数为1+4i,则输入1 4):" ;
cin>>b;
cout<<"请输入运算类型:";
cin>>e;
if(e == '+')
{
c = a + b;
cout<<c<<endl;
}
else if(e == '-')
{
c = a - b;
cout<<c<<endl;
}
else if(e == '*')
{
c = a * b;
cout<<c<<endl;
}
else if(e == '/')
{
c = a / b;
cout<<c<<endl;
}
}
}
return 0;
}