酷代码 AI
菜单
服务商

Python实现:圆形体(球、圆柱、圆锥)体积计算器代码详解

以下是使用Python实现的圆形体体积计算器的代码: ```python import math while True: print("1-Ball") print("2-Cylinder") print("3-Cone") print("other-Exit") print("Please enter your command:") command = int(input()) if command == 1: print("Please enter the radius:") r = float(input()) # 计算球体体积 volume = (4/3) * math.pi * r3 print("{:.2f}".format(volume)) elif command == 2: print("Please enter the radius and the height:") r, h = map(float, input().split()) # 计算圆柱体体积 volume = math.pi * r2 * h print("{:.2f}".format(volume)) elif command == 3: print("Please enter the radius and the height:") r, h = map(float, input().split()) # 计算圆锥体体积 volume = (1/3) * math.pi * r2 * h print("{:.2f}".format(volume)) else: break ``` 代码解释: 1. 导入模块:`import math` 用于导入数学模块,以便使用圆周率 `math.pi`。 2. 循环处理:使用 `while True` 构建一个无限循环,直到用户输入非1、2、3的整数时退出循环。 3. 输出指令界面:每次循环开始时,输出指令界面,提示用户输入指令。 4. 根据指令计算体积: - 当用户输入 `1` 时,提示用户输入球体半径,计算并输出球体体积。 - 当用户输入 `2` 时,提示用户输入底圆半径和高,计算并输出圆柱体体积。 - 当用户输入 `3` 时,提示用户输入底圆半径和高,计算并输出圆锥体体积。 5. 退出循环:当用户输入非1、2、3的整数时,使用 `break` 语句退出循环,结束程序。 注意事项: - 代码中使用了 `"{:.2f}".format(volume)` 来格式化输出结果,保留小数点后两位。 - 输入半径和高时,使用 `map(float, input().split())` 将输入的字符串按空格分割并转换为浮点数。 ######[AI问答 | 559点数解答 | 2025-12-10 20:33:40]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]