def写一个随机生成三个数字加减乘除运算结果为整数
时间: 2024-05-19 14:16:08 浏览: 179
import random
def generate_expression():
# 生成随机数
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
num3 = random.randint(1, 100)
# 随机选择操作符
operator1 = random.choice(['+', '-', '*', '/'])
operator2 = random.choice(['+', '-', '*', '/'])
# 计算结果
if operator1 == '+':
result = num1 + num2
elif operator1 == '-':
result = num1 - num2
elif operator1 == '*':
result = num1 * num2
else:
result = num1 / num2
# 如果结果不是整数,重新生成
if result != int(result):
generate_expression()
else:
# 继续计算
if operator2 == '+':
result = result + num3
elif operator2 == '-':
result = result - num3
elif operator2 == '*':
result = result * num3
else:
result = result / num3
# 如果结果不是整数,重新生成
if result != int(result):
generate_expression()
else:
# 返回表达式和结果
expression = f"{num1} {operator1} {num2} {operator2} {num3}"
return expression, int(result)
# 测试
for i in range(10):
expression, result = generate_expression()
print(f"{expression} = {result}")
阅读全文