两个英制长度的差异

时间:2014-07-10 21:11:41

标签: python algorithm python-3.x units-of-measurement negative-number

我有一个程序需要两个英制长度(英里,码,英尺和英寸)并输出它们的总和和差异。我的问题是,当差异为负时,输出是不正确的。

def to_inches(miles, yards, feet, inches):
    return inches + (feet * 12) + (yards * 36) + (miles * 63360)


def from_inches(inches):
    miles = inches // 63360
    inches %= 63360

    yards = inches // 36
    inches %= 36

    feet = inches // 12
    inches %= 12

    return (miles, yards, feet, inches)

units1 = [int(n) for n in input().split(' ')]
units2 = [int(n) for n in input().split(' ')]

m_sum = from_inches(to_inches(*units1) + to_inches(*units2))
m_diff = from_inches(to_inches(*units1) - to_inches(*units2))

print(' '.join(str(n) for n in m_sum))
print(' '.join(str(n) for n in m_diff))

输入:

2 850 1 7
1 930 1 4

输出:

4 21 0 11
0 1680 1 3

输入:

0 1 0 0
1 0 0 0

预期产出:

1 1 0 0
-0 1759 0 0

实际输出:

1 1 0 0
-1 1 0 0

1 个答案:

答案 0 :(得分:2)

这是因为Python在负数时处理mod运算符%有点奇怪。看看这个答案:https://stackoverflow.com/a/3883019/436282