C++多形状体积累加及总容积打印功能实现求助
问题原因
- 每次循环都重新创建
Volume类对象,之前计算的体积数据会被清空 - 类内只存储了单个形状的体积,没有对外暴露体积的读取方法,主函数无法获取数值做累加
- 存在拼写错误:
switch分支中case 3调用的cylender()和类内定义的cylinder()名称不匹配 return 0写在while(1)循环内部,程序第一次运行就会直接退出,无法实现多次计算累加的效果- 缺少存储总体积的变量,也没有对应的打印逻辑
- 头文件
iostream.h是C++98之前的过时写法,conio.h是非标准依赖,兼容性差
修复后完整代码
#include <iostream> using namespace std; class Volume { float V; public: void cube() { float a; cout << "Enter value of side" << endl; cin >> a; V = a * a * a; } void cuboid() { float l, b, h; cout << "Enter length,breadth & height of cuboid" << endl; cin >> l >> b >> h; V = l * b * h; } void cylinder() { float r, h; cout << "Enter radius & height of cylinder" << endl; cin >> r >> h; V = 3.14 * r * r * h; } void sphere() { float r; cout << "Enter radius of sphere" << endl; cin >> r; V = (4 * 3.14 * r * r * r) / 3; } void cone() { float r, h; cout << "Enter radius & height of cone" << endl; cin >> r >> h; V = (3.14 * r * r * h) / 3; } void display() { cout << "Current shape volume is = " << V << endl; } // 新增获取当前体积的方法 float getV() { return V; } }; int main() { float total_volume = 0; // 存储总体积的变量 Volume ob; // 把对象创建移到循环外,避免每次重置 while(1){ int ch; cout << "Select the shape for calculate volume" << endl << endl; cout << "Press 1 for select CUBE" << endl; cout << "Press 2 for select CUBOID" << endl; cout << "Press 3 for select CYLINDER" << endl; cout << "Press 4 for select SPHERE" << endl; cout << "Press 5 for select CONE" << endl; cout << "Press 0 to EXIT and show total volume" << endl << endl; cin >> ch; cout << endl; if(ch == 0) break; // 按0退出循环 switch(ch) { case 1: ob.cube();break; case 2: ob.cuboid();break; case 3: ob.cylinder();break; // 修复拼写错误 case 4: ob.sphere();break; case 5: ob.cone();break; default: cout << "Wrong input" << endl; continue; // 错误输入直接回到选择界面 } ob.display(); total_volume += ob.getV(); // 累加当前体积到总容积 cout << "Current total volume of all shapes is = " << total_volume << endl << endl; } // 退出后打印最终总体积 cout << "Final total volume of all shapes is = " << total_volume << endl; return 0; }
修改说明
- 新增了
getV()公共方法,主函数可以读取单个形状的体积做累加 - 在主函数中定义了
total_volume变量存储总体积,每次计算完单个形状就更新数值 - 修复了方法名拼写错误和
return 0的位置错误 - 移除了非标准的
conio.h依赖,改为按0直接退出的交互逻辑,兼容性更好 - 每次计算完都会显示当前总容积,退出时也会打印最终的累加结果
内容的提问来源于stack exchange,提问作者Amey Dubey
相关产品推荐
相关产品推荐

