码迷,mamicode.com
首页 > 编程语言 > 详细

四则运算 Python

时间:2016-03-06 15:35:31      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

要求:要求编写一道程序,随机给出30道四则运算题,除了整数意外还包括真分数的运算

思路

一:产生数字1,2计算是整数运算还是分数运算

用一个大循环据统计能打出需要的满足要求的个数,另一个统计实际数量

  1随机产生第一数字
  2随机产生字符数字,用4计算算符
  3随机产生第二数字
  4判断结果是否满足要求

  1随机产生第一数字,用两个随机数产生
  2随机产生字符数字,用4计算算符
  3随机产生第二数字,用两个随机数产生
  4判断结果是否满足要求

#writher gu peng
#edit date 20160305

from fractions import Fraction
from random import randint
amount=30
acc_amount=0
while acc_amount!=amount:
all_random=randint(1,2)
if (all_random==1):
first_num=randint(0,10)
second_num=randint(0,10)
opreation_num=randint(1,4)#计算结果
if(opreation_num==4): #/
if(second_num==0):
while second_num==0:
second_num=randint(0,10)
result=first_num/second_num
if(opreation_num==1):#+
result=first_num+second_num
if(opreation_num==2): #-
result=first_num-second_num
if(opreation_num==3): #*
result=first_num*second_num
if(result<=100 and result>=0): #判断结果 判断被除数是否为零
#判断结果是否在允许范围内
print first_num,
if(opreation_num==4): #/
print"/",
if(opreation_num==1):#+
print"+",
if(opreation_num==2): #-
print"-",
if(opreation_num==3): #*
print"*",
print second_num
acc_amount=acc_amount+1

if (all_random==2):
first_num1=randint(0,10)
first_num2=randint(1,10)
second_num1=randint(0,10)
second_num2=randint(1,10)

while first_num1>=first_num2:
first_num1=randint(0,10)
first_num2=randint(1,10)
while second_num1>=second_num2:
second_num1=randint(0,10)
second_num2=randint(1,10)

first_num=Fraction(first_num1, first_num2)
second_num=Fraction(second_num1,second_num2)

opreation_num=randint(1,4)#计算结果
if(opreation_num==4): #/
if(second_num==0):
while second_num2==0 or second_num1==0:
second_num1=randint(0,10)
second_num2=randint(1,10)
second_num=Fraction(second_num1,second_num2)
result=first_num/second_num
if(opreation_num==1):#+
result=first_num+second_num
if(opreation_num==2): #-
result=first_num-second_num
if(opreation_num==3): #*
result=first_num*second_num
if(result<=100 and result>=0):
#if()
print "(",
print first_num,
print")",
if(opreation_num==4): #/
print"/",
if(opreation_num==1):#+
print"+",
if(opreation_num==2): #-
print"-",
if(opreation_num==3): #*
print"*",
print "(",
print second_num,
print")"
acc_amount=acc_amount+1

四则运算 Python

标签:

原文地址:http://www.cnblogs.com/Megau/p/5247495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!