第一周作业.四则运算生成器(基于python)

题目

从《构建之法》第一章的 “程序” 例子出发,像阿超那样,花二十分钟写一个能自动生成小学四则运算题目的命令行 “软件”,满足以下需求:

除了整数以外,还要支持真分数的四则运算,真分数的运算,例如:1/6 + 1/8 = 7/24
运算符为 +, −, ×, ÷
并且要求能处理用户的输入,并判断对错,打分统计正确率。
要求能处理用户输入的真分数, 如 1/2, 5/12 等
使用 -n 参数控制生成题目的个数,例如执行下面命令将生成10个题目
Myapp.exe -n 10

需求分析

1.需要生成随机数
2.循环结构生成相应数目的题目
3.判断题目的对错,并统计正确率
4.使用python2.7实现

程序

# coding=gbk
import random
import fractions
import string
i=0
result=0
temp=0
print"请输入想要生成的题目数量:"
n=input()
while i<n:

    first_num=random.randint(1,10)
    second_num=random.randint(1,10)
    third_num=random.randint(1,10)
    fourth_num=random.randint(1,10)
    a = random.choice("+-*/")
    if second_num==1:
        x=first_num
    else:
        x=fractions.Fraction(first_num,second_num)
    if fourth_num==1:
        y=second_num
    else:
        assert isinstance(fourth_num, object)
        y=fractions.Fraction(second_num,fourth_num)
    if a=="+":
        result=x+y
        faker=str(result)

        print  x,a,y,"="
    elif a=="-":
        result=x-y
        faker=str(result) #生成字符型
        print x,a,y,"="
    elif a=="*":
        result=x*y
        faker=str(result)
        print x,"x",y,"="
    elif a=="/":
        result=x/y
        faker=str(result)
        print x,"÷",y,"="
    answer=raw_input()

    if faker ==answer:         # 正确
        temp=temp+1
        print "right!"
    else:                         # 错误
        print 'error. the right answer is %s' % result
    i += 1
print  "您答对%d题" % temp

测试

自评

可以实现基本的分数运算,python这门语言也是刚开始学习,不足之处还有很多,请多多指教!

psp

代码地址(coding)

https://coding.net/u/run-in-way/p/homework/git/blob/master/sizeyunsuan.py

原文地址:https://www.cnblogs.com/haogege/p/6498668.html