#include <iostream>
#include <cmath>
using namespace std;
class calc //類名:calc(計算器)
{
private:
int a,b;
int p,m;
public:
calc(){} //不帶參數的構造函數
void input();
void input1();
void input2();
void input3();
void input4();
void input5();
double input6();
int jia();
int jian();
int mul();
int div();
//long pow(); //平方
void display1(); //加
void display2(); //減
void display_mul();
void display_div();
int display_pow(int); //以上均為成員函數
};
//以下是對成員函數的定義
int calc::jia()
{
//int sum;
//sum=a+b;
//return sum;
return a+b;
}
int calc::jian()
{
return a-b;
}
int calc::mul()
{
return a*b;
}
int calc::div()
{
if(b==0) //除數不能為0
{
cout<<"除數為零!請重新輸入..."<<endl;
cout<<"請輸入兩個整數:";
cin>>a>>b;
return 1;
}
else
return a/b;
}
//long calc::pow()
//{
// return p*p;
//}
void calc::input()
{
cout<<"請輸入兩個整數:";
cin>>a>>b;
}
void calc::input1()
{
input();
jia();
}
void calc::input2()
{
input();
jian();
}
void calc::input3()
{
input();
mul();
}
void calc::input4()
{
input();
div();
}
/*
void calc::input5()
{
input();
pow();
}
*/
double calc::input6()
{
cout<<"請輸入一個整數,求該數的平方根:";
cin>>m;
double q=sqrt(m);
return q;
}
void calc::display1()
{
cout<<"兩數之和="<<jia()<<endl;
}
void calc::display2()
{
cout<<"兩數之差="<<jian()<<endl;
}
void calc::display_mul()
{
cout<<"兩數之積="<<mul()<<endl;
}
void calc::display_div()
{
cout<<"兩數之商="<<div()<<endl;
}
int calc::display_pow(int q)
{
return q*q;
}
//菜單
void menu()
{
cout<<"*********************************"<<endl;
cout<<endl;
cout<<" ===簡單計算器==="<<endl;
cout<<endl;
cout<<" ---1.加---"<<endl;
cout<<endl;
cout<<" ---2.減---"<<endl;
cout<<endl;
cout<<" ---3.乘---"<<endl;
cout<<endl;
cout<<" ---4.除---"<<endl;
cout<<endl;
cout<<" ---5.平方---"<<endl;
cout<<endl;
cout<<" ---6.平方根---"<<endl;
cout<<endl;
cout<<" ---0.退出---"<<endl;
cout<<endl;
cout<<"*********************************"<<endl;
}
//退出菜單
void _exit()
{
cout<<"*********************************"<<endl;
cout<<endl;
cout<<" 歡迎使用本系統"<<endl;
cout<<endl;
cout<<endl;
cout<<" ---再見---"<<endl;
cout<<endl;
cout<<"*********************************"<<endl;
}
////////////主函數/////////////
int main()
{
calc add;
calc sub;
calc mul;
calc div;
calc pow;
calc sqrt; //以上用類定義對象
int c;
menu(); //調用主菜單
while(1)
{
cout<<"請選擇:";
cin>>c;
switch(c)
{
case 1:
add.input1();
add.display1();
break;
case 2:
sub.input2();
sub.display2();
break;
case 3:
mul.input3();
mul.display_mul();
break;
case 4:
div.input4();
div.display_div();
break;
case 5:
//pow.input5();
int p;
cout<<"請輸入一個正整數:";
cin>>p;
cout<<"該數的平方是:"<<pow.display_pow(p)<<endl;
break;
case 6:
cout<<"該數的平方根為:"<<sqrt.input6()<<endl;
break;
case 0:
system("cls");
_exit();
exit(1);
break;
default:
cout<<"輸入錯誤!"<<endl;
break;
}
}
return 1;
}
運行結果: