首页 > 其他 > 详细

简单的四则运算

时间:2020-10-11 21:01:08      阅读:34      评论:0      收藏:0      [点我收藏+]
import numpy as np

def noAnwser():
    num = 10
    while(num):
        op = [+, -, "*", /]
        x = np.random.randint(101)
        y = np.random.randint(101)
        z = np.random.randint(101)
        num1 = np.random.randint(4)
        num2 = np.random.randint(4)
        expression = [x, op[num1], y, op[num2], z]

        # 被除数不能为0
        if (op[num1] == / and y == 0) or (op[num2] == / and z == 0):
            continue

        num = num - 1
        for elem in expression:
            print(str(elem) + " ", end="")
        print("= ")

def Anwser():
    num = 10
    while(num):
        op = [+, -, "*", /]
        x = np.random.randint(101)
        y = np.random.randint(101)
        z = np.random.randint(101)
        num1 = np.random.randint(4)
        num2 = np.random.randint(4)
        expression = [x, op[num1], y, op[num2], z]
        exp = ""
        mid = ""

        # 被除数不能为0
        if (op[num1] == / and y == 0) or (op[num2] == / and z == 0):
            continue
            
        # 判断计算顺序写出表达式
        if num1 <= 1 and num2 > 1:
            mid = str(expression[2]) + str(expression[3] + str(expression[4]))
            exp = str(expression[0]) + str(expression[1]) + str(eval(mid))
        else:
            for j in expression:
                exp = exp + str(j)

        # 对结果进行约束
        if eval(exp) <= 100 and eval(exp) >= 0:
            for elem in expression:
                print(str(elem) + " ", end="")
            num = num - 1
            print("= " + str(eval(exp)))

if __name__ == "__main__":
    noAnwser()

输出结果:

1. 两个运算符,100以内的数字,不需要写答案

技术分享图片

 

 2. 需要写答案,答案在0-100之间

技术分享图片

 

简单的四则运算

原文:https://www.cnblogs.com/newgoals/p/13798985.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!