基本上,我从大学得到了家庭作业,用户必须输入 x 盎司量,所有这些都会被转换并以石头、磅和剩余盎司的形式打印到屏幕上。我已经坚持了将近一个星期。这是我到目前为止设法完成的代码:
inp = int(input("Enter your weight in ounces: "))
stones = int(inp / 224)
inp1 = int(inp - (stones * 14))
pounds = int(inp1 % 16)
print(stones ,"Stones", pounds, "Pounds")
石头钻头工作完美,但我想知道您如何获得剩余的盎司并将其转换为磅然后再转换为盎司?
更好的方法是先将盎司换算成磅,然后再将磅换算成英石。
def convert(total_ounces):
ounces = total_ounces % 16
total_pounds = total_ounces//16 # 1 pound = 16 ounces
pounds = total_pounds % 14
stones = total_pounds//14 # 1 stone = 14 pounds
print stones, " stones ", pounds, "pounds", ounces, " ounces"
>>> convert (110)
0 stones 6 pounds 14 ounces
>>> convert (500)
2 stones 3 pounds 4 ounces
以及您的代码存在的问题:
inp = int(input("Enter your weight in ounces: "))
stones = int(inp / 224) # Here you get the maximum no of stones. You
# should better be using inp // 224 rather
# that int(inp / 224).
inp1 = int(inp - (stones * 14)) # Firstly, since both inp and stones*14 would
# be int so there is no need for using int().
# and what I think you are trying to do here
# is finding the remaining no of ounces, so
# you should be doing something like
# inp1 = inp - stones * 14 * 16
pounds = int(inp1 % 16) # again here there is no need of using int.
# And inp1 % 16 should return the number of
# ounces not pounds. Pounds should be inp1 // 16 .
print(stones ,"Stones", pounds, "Pounds")
我是一名优秀的程序员,十分优秀!