酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

请编写一个基于对象的程序。数据成员包括length(长)、width(宽)、height(高).要求用成员函数实现以下功能 (1)由键盘分别输入3个长方柱的长宽高。 (2)计算长方柱的体积 (3)输出3个长方柱的体积 输入样例: 1 2 3↙ 2 3 4↙ 3 4 5↙ 输出样例: 6↙ 24↙ 60↙

以下是用 C++实现的代码: ```cpp #include <iostream> using namespace std; class Cuboid { private: double length; double width; double height; public: // 输入长宽高的函数 void inputDimensions() { cout << "请输入长: "; cin >> length; cout << "请输入宽: "; cin >> width; cout << "请输入高: "; cin >> height; } // 计算体积的函数 double calculateVolume() { return length * width * height; } // 输出体积的函数 void outputVolume() { cout << calculateVolume() << endl; } }; int main() { Cuboid cuboids[3]; for (int i = 0; i < 3; i++) { cuboids[i].inputDimensions(); } for (int i = 0; i < 3; i++) { cuboids[i].outputVolume(); } return 0; } ``` 额外需要注意的逻辑点: 1. 要对用户输入的数据进行有效性检查,比如是否为正数。 2. 考虑异常处理,比如输入不是数字的情况。 3. 代码的可扩展性,比如后续如果要增加更多的形状计算,如何方便修改。 [2024-12-16 12:46:10 | AI写代码神器 | 320点数解答]

相关提问