Github链接:https://github.com/kelikel/work_first

(1)题目

能自动生成小学四则运算题目(结果不出现负数);

除了整数外,还要支持真分数的四则运算。

对原四则运算进行功能上的改进

(2)PSP表格:

(3)需求分析:

满足小学的基础计算且不超纲;

随机生成四则运算题,结果不为负数;

存在真分数的计算;

可生成答案进行对比;

每道题都可由用户输入答案并进行判断,累计输出答对的题目。

(4)解题思路:

小学的运算只有加减乘除,且需要满足不出现负数的情况,因为运算中减法可能出现负数情况,需要对随机生成的两个数字进行比较,将较大的作为被减数,较小的作为减数,解决负数出现的问题;

为解决真分数问题,调用 fractions 进行真分数运算

(5)设计实现:

newint( )函数生成整数四则运算

newfra( )函数生成真分数四则运算

newtest( )函数生成题库及答案

用if 判断选择进入不同的选择阶段

(6)代码实现:

import random

from fractions import Fraction
def newint(): 
    opr = ['', '', '×', '÷']
    fh = random.randint(0, 3)
    n1 = random.randint(1, 20)
    n2 = random.randint(1, 20)
    rjg = 0
    if fh == 0:
        rjg = n1 + n2
    elif fh == 1:
        n1, n2 = max(n1, n2), min(n1, n2)
        rjg = n1 - n2
    elif fh == 2:
        rjg = n1 * n2
    elif fh == 3:
        n1, n2 = max(n1, n2), min(n1, n2)
        while n1 % n2 != 0:
            n1 = random.randint(1, 20)
            n2 = random.randint(1, 20)
            n1, n2 = max(n1, n2), min(n1, n2)
        rjg = int(n1 / n2)
    print(n1, opr[fh], n2, '= ', end='')
    return rjg

def newfra():
    opr = ['', '', '×', '÷']
    fh = random.randint(0, 3)
    t1 = random.randint(1, 10)
    t2 = random.randint(t1, 10)
    n1 = Fraction(t1, t2)
    t1 = random.randint(1, 10)
    t2 = random.randint(t1, 10)
    n2 = Fraction(t1, t2)
    rjg = 0
    if fh == 0:
        rjg = n1 + n2
    elif fh == 1:
        n1, n2 = max(n1, n2), min(n1, n2)
        rjg = n1 - n2
    elif fh == 2:
        rjg = n1 * n2
    elif fh == 3:
        n1, n2 = max(n1, n2), min(n1, n2)
        rjg = n1 / n2
    print(n1, opr[fh], n2, '= ', end='')
    return rjg

def newtest():
    opr = ['', '', '×', '÷']
    print('输入题库所需要的题目数量')
    n=int(input())
    rjg=[]
    m=0
    while m<=(n-1):
        fh = random.randint(0, 4)
        if fh==0:
            print(m+1,end='. ')
            rjg.append(newfra())
            print(' ')
        else:
            print(m+1,end='. ')
            rjg.append(newint())
            print(' ')
        m=m+1
    m=0
    print('答案:')
    while m<=(n-1):
        print(m+1,'. ',rjg[m])
        m=m+1


print('按1进入答题判断')
print('按2进入题库生成')
n=int(input())
if n==1:
    print('输入"1111"结束本轮')
    while True:
        fh=random.randint(0,4)
        if fh==0:
            rjg = newfra()
            jg = input()
            if jg == '1111':
                break;
            sr = Fraction(jg)
            if sr == rjg:
                print('答案正确!')
            else:
                print('答案错误,正确答案为:', rjg)
        else:
            rjg = newint()
            jg = input()
            if jg == '1111':
                break;
            sr = int(jg)
            if sr == rjg:
                print('答案正确!')
            else:
                print('答案错误,正确答案为:', rjg)
if n==2:
    newtest()

(7)运行结果:

版权声明:本文为jigxn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/jigxn/p/10606421.html