小學四則運算程式設計實踐
阿新 • • 發佈:2020-11-29
1 import random#匯入隨機庫 2 from fractions import Fraction#匯入分數運算 3 ##整數運算 4 def c1(q, ans): 5 operator = random.choice(['+', '-', '*', '/']) # 生成運算子 6 if operator == '+': 7 n1 = random.randint(0, 10) 8 n2 = random.randint(0, 10) 9 q.append(str(n1) + '+' + str(n2) + '=') 10 ans.append(n1 + n2) 11 elif operator == '-': 12 n1 = random.randint(0, 10) 13 n2 = random.randint(0, 10) 14 n1, n2 = max(n1, n1), min(n1, n2) # 防止出現負數 15 q.append(str(n1) + '-' + str(n2) + '=') 16 ans.append(n1 - n2) 17 elif operator == '*':18 n1 = random.randint(0, 10) 19 n2 = random.randint(0, 10) 20 q.append(str(n1) + '×' + str(n2) + '=') 21 ans.append(n1 * n2) 22 else: 23 n1 = random.randint(0, 10) 24 n2 = random.randint(1, 10) 25 q.append(str(n1) + '÷' + str(n2) + '=') 26 ans.append(Fraction(n1, n2))27 ##隨機生成兩個分數,且第二個不為0 28 def createF(): 29 fz1 = random.randint(0, 10) 30 fm1 = random.randint(1, 10) 31 f1 = Fraction(fz1, fm1) 32 fz2 = random.randint(1, 10) 33 fm2 = random.randint(1, 10) 34 f2 = Fraction(fz2, fm2) 35 return f1, f2 36 def f(f): # 分數的轉換 37 a = f.numerator # 分子 38 b = f.denominator # 分母 39 if a % b == 0: # 為整數 40 return '%d' % (a/b) 41 elif a < b: # 為真分數 42 return '%d%s%d' % (a, '/', b) 43 else: # 為帶分數 44 c = int(a/b) 45 a = a - c * b 46 return '%d%s%d%s%d' % (c, '’', a, '/', b) 47 ##分數運算 48 def c2(q, ans): 49 operator = random.choice(['+', '-', '*', '/']) 50 f1, f2 = createF() 51 if operator == '+': 52 f1, f2 = createF() 53 q.append(str(f1)+'+'+str(f2)+'=') 54 ans.append(f1+f2) 55 elif operator == '-': 56 f1, f2 = max(f1, f2), min(f1, f2) # 防止出現負數 57 q.append(str(f1)+'-'+str(f2)+'=') 58 ans.append(f1-f2) 59 elif operator == '*': 60 f1, f2 = createF() 61 q.append(str(f1)+'×'+str(f2)+'=') 62 ans.append(f1*f2) 63 else: 64 f1, f2 = createF() 65 q.append(str(f1)+'÷'+str(f2)+'=') 66 ans.append(Fraction(f1, f2)) 67 def main(): 68 while 1: 69 k = 10 70 p = 10 71 s = 0 72 q = [] 73 ans = [] 74 ans2 = [] 75 for i in range(k): 76 n = random.randint(1, 4) 77 if n == 1: 78 c1(q, ans) 79 g = Fraction(ans[i]) 80 ans2.append(f(g)) 81 else: 82 c2(q, ans) 83 g = Fraction(ans[i]) 84 ans2.append(f(g)) # 記錄帶分數答案 85 for i in range(k): 86 print("第{}題:{}".format(i + 1, q[i]), end=" ") 87 a = input() 88 if a == str(ans[i]): 89 s = s + p 90 print("所得的分數為:{}".format(s)) 91 print("正確答案:", end=" ") 92 for i in range(k): 93 if str(ans[i]) == str(ans2[i]): 94 print(q[i] + str(ans[i])) 95 else: 96 print("{}{}或{}".format(q[i], str(ans2[i]), str(ans[i]))) 97 if __name__ == '__main__': 98 main()