编写有几个四则运算的程序,要求加减乘除各定义为一个函数来实现
时间: 2024-05-09 20:19:29 浏览: 101
以下是一个Python实现的例子:
```
import operator
import random
# 定义加减乘除四个函数
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
# 定义生成随机题目的函数
def generate_question():
ops = {'+': add, '-': subtract, '*': multiply, '/': divide}
op = random.choice(list(ops.keys()))
x = random.randint(0, 100)
y = random.randint(1, 100)
if op == '/' and x % y != 0: # 除法运算结果不为整数时重新生成
return generate_question()
return x, y, op, ops[op]
# 主函数,生成10道题目并输出
if __name__ == '__main__':
for i in range(10):
x, y, op, func = generate_question()
result = func(x, y)
print(f'{x} {op} {y} = {result:.2f}')
```
运行结果示例:
```
18 * 54 = 972.00
32 + 5 = 37
54 / 6 = 9.00
99 - 60 = 39
11 + 27 = 38
13 * 27 = 351.00
88 / 22 = 4.00
71 - 25 = 46
3 * 1 = 3.00
66 + 19 = 85
```
阅读全文