用cpp类与对象应用:一长方形形游泳池如图所示,现在需在其周围建一过道,并在其四周围上栅栏。过道宽度为3米,造价为20元/平方米;外围栅栏价格为50元/米。游泳池长宽由键盘输入,设计一个矩形类,计算并输出过道和栅栏的造价。
时间: 2024-03-26 21:38:42 浏览: 13
好的,我来帮你解决这个问题。首先,我们需要设计一个矩形类,该类应该包含长和宽两个数据成员,并且应该有计算面积和周长的成员函数。接下来,在该类中添加一个计算过道和栅栏造价的成员函数。具体实现如下:
```cpp
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}
double perimeter() {
return 2 * (length + width);
}
double cost() {
double area1 = (length + 6) * (width + 6) - length * width;
double area2 = (length + 6) * 2 + (width + 6) * 2 - 24;
double cost1 = area1 * 20;
double cost2 = area2 * 50;
return cost1 + cost2;
}
};
int main() {
double l, w;
cout << "请输入游泳池的长和宽:";
cin >> l >> w;
Rectangle rect(l, w);
cout << "过道和栅栏的造价为:" << rect.cost() << "元" << endl;
return 0;
}
```
在上述代码中,我们定义了一个 Rectangle 类,该类有两个私有数据成员 length 和 width,分别表示长和宽。然后,我们在类中定义了三个公有成员函数 area()、perimeter() 和 cost(),分别用于计算矩形的面积、周长和过道和栅栏的造价。在 cost() 函数中,我们首先计算出过道的面积和栅栏的周长,然后分别乘以对应的单价,最后将两者相加得到总造价。
在主函数中,我们首先从键盘输入游泳池的长和宽,然后创建一个 Rectangle 类的对象 rect,并调用其 cost() 函数计算过道和栅栏的造价,最后输出结果即可。
注意,我们在计算过道的面积和栅栏的周长时都需要加上6米的过道宽度,同时减去游泳池内部的面积和过道的面积(即 length * width)。在计算栅栏的周长时,还需要减去四个角落的长度(即 2 * 3 * 4 = 24 米)。