定义一个矩形类,有长、宽两个属性,有成员函数计算矩形的面积
解:
#include <iostream.h> class Rectangle { public: Rectangle(float len, float width) { Length = len; Width = width; } ~Rectangle(){}; float GetArea() { return Length * Width; } float GetLength() { return Length; } float GetWidth() { return Width; } private: float Length; float Width; }; void main() { float length, width; cout << "请输入矩形的长度:"; cin >> length; cout << "请输入矩形的宽度:"; cin >> width; Rectangle r(length, width); cout << "长为" << length << "宽为" << width << "的矩形的面积为:" << r.GetArea () << endl; }
程序运行输出:
请输入矩形的长度:5
请输入矩形的宽度:4
长为 5 宽为 4 的矩形的面积为:20
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
解:
#include <iostream.h> class Rectangle { public: Rectangle(float len, float width) { Length = len; Width = width; } ~Rectangle(){}; float GetArea() { return Length * Width; } float GetLength() { return Length; } float GetWidth() { return Width; } private: float Length; float Width; }; void main() { float length, width; cout << "请输入矩形的长度:"; cin >> length; cout << "请输入矩形的宽度:"; cin >> width; Rectangle r(length, width); cout << "长为" << length << "宽为" << width << "的矩形的面积为:" << r.GetArea () << endl; }程序运行输出:
请输入矩形的长度:5
请输入矩形的宽度:4
长为 5 宽为 4 的矩形的面积为:20