如何始终获得正输出?

时间:2013-12-16 17:46:14

标签: python python-3.x integer

这是我的代码:

import random
minimum=int(input("Enter minimum value: "))
maximum=int(input("Enter maximum value: "))
if minimum>maximum:
    temp=minimum
    minimum=maximum
    maximum=temp
howMany = int(input("How many numbers do you want to generate?"))
sum=0
n=1
while n<=howMany:
    num=random.randrange(minimum,maximum)
    sum+=num
    n+=1
    print("Your random generated number is",num)
print("Python's random average between", minimum, "and", maximum, "is", sum/howMany)
avg=minimum+maximum/2
avgTwo=sum/howMany
difference=avgTwo-avg
print("The actual average of minimum and maximum is", avg)
print("The difference from the calculated average and from the actual average is", difference)

当我计算差异时,我需要总是得到一个正数。我尝试翻转被减去的变量,但我在随机时间收到一个负数。

3 个答案:

答案 0 :(得分:3)

您可以取差值的绝对值来获得两个值之间的“距离”:

>>> abs(2 - 5)
3
>>> abs(5 - 2)
3

答案 1 :(得分:0)

如果值为负,则简单地将值乘以-1,以便最终结果为正:

difference= avgTwo-avg if avgTwo-avg > 0 else (avgTwo-avg) * -1

答案 2 :(得分:0)

以下是有关改进代码的一些提示:

from random import randrange   #import only what need
mini = int(input("Enter minimum value: "))
maxi = int(input("Enter maximum value: "))
if mini > maxi:
    mini, maxi = maxi, mini   #you can swap two values like this

howMany = int(raw_input("How many numbers do you want to generate?"))
total = 0  # don't use sum as variable name, it is built in function
for _ in range(howMany):  #you can use a for loop and not have increment a counter
    num = randrange(mini, maxi+1) #add 1 to maxi to get the range you want
    print("Your random generated number is ", num)
    total += num

print("Python's random average between", mini, "and", maxi, "is", total/howMany)
avg = (mini + maxi)/2  # use ()'s for proper operation order
avgTwo = total/howMany
difference = abs(avgTwo - avg)  #use absolute value to get magnitude
print("The actual average of minimum and maximum is", avg)
print("The difference from the calculated average and from the actual average is", difference)