【问题标题】:Difference of two imperial lengths两个英制长度之差
【发布时间】:2014-09-01 09:48:15
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 显然,整数除法运算符 (//) 也是如此。所以我最终使用了int(math.fmod(x, y))int(x / y)。另外,我添加了一个检查,如果其中任何一个为负数,则仅将第一个数字设为负数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多