求助怎么随机生成一个两次运算的加减算式
算式是一个数随机进行两次运算 (加1加1 或加1减1 或减1加1 或减1减1)要求结果在0~9之间{:10_266:} 用随机数,判断如果为偶数就加否则就减重复两次即可 这里我只给出python的代码:
import random as r
while 1:
num = r.randint(0, 9)
str1 = str(r.choice('+' '-'))
str2 = str(r.choice('+' '-'))
fomula = ('%d%s1%s1' % (num, str1, str2))
if (str1 == '+' and str2 == '+'):
result = num + 1 + 1
elif (str1 == '+' and str2 == '-'):
result = num + 1 - 1
elif (str1 == '-' and str2 == '+'):
result = num - 1 + 1
elif (str1 == '-' and str2 == '-'):
result = num - 1 - 1
if result >= 10 or result < 0:
continue
else:
print('%s=%d' % (fomula, result))
break
希望能对你起到帮助!
页:
[1]