Files
AIcode/math.py
group04_tangzhuoyang 420bbac9d7 Replace palindrome function with multiply and divide operations
- Add multiply() function for multiplication
- Add divide() function with zero divisor check
- Add comprehensive test cases and interactive mode
- Remove palindrome detection functionality
2026-04-02 15:03:50 +08:00

156 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
math.py - 数学运算工具
提供乘法和除法运算功能
"""
def multiply(a: float, b: float) -> float:
"""
计算两个数的乘积
参数:
a: 第一个数
b: 第二个数
返回:
两个数的乘积
"""
return a * b
def divide(a: float, b: float) -> float:
"""
计算两个数的除法
参数:
a: 被除数
b: 除数
返回:
除法结果
异常:
ValueError: 当除数为0时抛出
"""
if b == 0:
raise ValueError("除数不能为0")
return a / b
def test_operations():
"""测试乘法和除法运算"""
print("测试乘法运算:")
print("-" * 30)
# 测试乘法
test_cases_multiply = [
(2, 3, 6),
(0, 5, 0),
(-3, 4, -12),
(2.5, 4, 10.0),
(-2.5, -4, 10.0),
(0, 0, 0),
]
for a, b, expected in test_cases_multiply:
result = multiply(a, b)
status = "" if abs(result - expected) < 1e-10 else ""
print(f"{a} × {b} = {result} {status} (期望: {expected})")
print("\n测试除法运算:")
print("-" * 30)
# 测试除法
test_cases_divide = [
(6, 2, 3),
(10, 4, 2.5),
(-12, 3, -4),
(0, 5, 0),
(7.5, 2.5, 3),
(-10, -2, 5),
]
for a, b, expected in test_cases_divide:
try:
result = divide(a, b)
status = "" if abs(result - expected) < 1e-10 else ""
print(f"{a} ÷ {b} = {result} {status} (期望: {expected})")
except ValueError as e:
print(f"{a} ÷ {b} = 错误: {e}")
# 测试除数为0的情况
print("\n测试除数为0的情况:")
print("-" * 30)
zero_test_cases = [
(5, 0),
(0, 0),
(-3, 0),
(10.5, 0),
]
for a, b in zero_test_cases:
try:
result = divide(a, b)
print(f"{a} ÷ {b} = {result} ✗ (应该抛出异常)")
except ValueError as e:
print(f"{a} ÷ {b} = 正确抛出异常: {e}")
def interactive_mode():
"""交互式模式"""
print("\n" + "=" * 40)
print("交互式计算模式 (输入 'exit' 退出)")
print("=" * 40)
while True:
print("\n选择操作:")
print("1. 乘法")
print("2. 除法")
print("exit. 退出")
choice = input("请选择 (1/2/exit): ").strip().lower()
if choice == 'exit':
print("退出交互模式。")
break
if choice not in ['1', '2']:
print("无效选择,请重新输入。")
continue
try:
a = float(input("请输入第一个数: "))
b = float(input("请输入第二个数: "))
if choice == '1':
result = multiply(a, b)
print(f"{a} × {b} = {result}")
elif choice == '2':
try:
result = divide(a, b)
print(f"{a} ÷ {b} = {result}")
except ValueError as e:
print(f"错误: {e}")
except ValueError:
print("错误:请输入有效的数字。")
def main():
"""主函数"""
print("数学运算工具测试")
print("=" * 40)
# 运行测试
test_operations()
# 询问是否进入交互模式
choice = input("\n是否进入交互式计算模式? (y/n): ").strip().lower()
if choice == 'y':
interactive_mode()
else:
print("程序结束。")
if __name__ == "__main__":
main()