题目
1设计长方体类
题目描述
求3个长方柱的体积,请编写一个基于对象的程序。数据成员包括length,width,height。
要求用成员函数实现以下功能:
(1) 由键盘分别输入3个长方柱的长、宽、高;
(2) 计算长方柱的体积;
(3) 输出3个长方柱的体积。
请编程序,上机调试并运行。
输入
三个长方柱的长、宽、高(直接输入数值,无需提示信息)
输出
三个长方柱的体积,输出格式为
volmue of box1 is XX volmue of box2 is XX volmue of box3 is XX
答案
#include <iostream>
class Cube {
public:
double length;
double width;
double height;
Cube() {}
void setDimensions(double l, double w, double h) {
length = l;
width = w;
height = h;
}
double getVolume() {
return length * width * height;
}
};
int main() {
Cube box1, box2, box3;
double
volume;
std::cout << "Enter the dimensions for box1 (length, width, height): ";
double l1, w1, h1;
std::cin >> l1 >> w1 >> h1;
box1.setDimensions(l1, w1, h1);
std::cout << "Enter the dimensions for box2 (length, width, height): ";
double l2, w2, h2;
std::cin >> l2 >> w2 >> h2;
box2.setDimensions(l2, w2, h2);
std::cout << "Enter the dimensions for box3 (length, width, height): ";
double l3, w3, h3;
std::cin >> l3 >> w3 >> h3;
box3.setDimensions(l3, w3, h3);
std::cout << "Volume of box1 is " << box1.getVolume() << std::endl;
std::cout << "Volume of box2 is " << box2.getVolume() << std::endl;
std::cout << "Volume of box3 is " << box3.getVolume() << std::endl;
return 0;
}