代码练习
计算矩形周长与面积
#include <iostream>
using namespace std;
//封装一个矩形类(Rect)
//拥有私有属性:宽度(wide)、高度(hight)
//定义成员函数:初始化函数、更改宽度的函数、更改高度的函数、输出矩形周长和面积的函数
class Rect
{
private:
int wide;
int hight;
public:
void init(int w,int h)
{
wide = w;
hight = h;
}
void ch_wide()
{
cout << "请输入宽度" << endl;
cin >> wide ;
}
void ch_hight()
{
cout << "请输入高度" << endl;
cin >> hight;
}
void show()
{
cout << "周长: " << ((wide*2)+hight*2) << endl;
cout << "面积: " << (wide*hight) <<endl;
}
};
int main()
{
Rect rec;
int w;
int h;
cout << "请输入宽度: " << endl;
cin >> w;
cout << "请输入高度: " << endl;
cin >> h;
rec.init(w,h);
while(1)
{
system("CLS");
rec.show();
cout << "按1进行计算矩形周长与面积" << endl;
cout << "按0退出" << endl;
int key;
cout << "请输入选项" << endl;
cin >> key ;
switch (key)
{
case 0:
{
goto END;
}
break;
case 1:
{
rec.ch_wide();
rec.ch_hight();
rec.show();
}
break;
}
}
END:
cout << "退出成功" << endl;
return 0;
}
效果演示
矩形周长面积计算