好的,我已经编写了我的代码,这样用户可以输入7个数字,并将奇数索引数字乘1,偶数索引数字乘3:
num = str(input("Please enter 7 numbers")
length = len(num)
while length < 7 or length ? 7:
num = input("Only enter 7 numbers")
string = ''
for t in range(1,8):
if t % 2 == 0:
string += str(t * 3)
else:
string += str(t) + ' '
print(string)这很好用,但是现在我需要把所有的数字相加,然后从最高的10中减去它,例如,所有的数字加起来就是53,我需要从60中减去它,剩下的是7,那将是我的8个数字,然后在我得到那个数字后,我打印出来,我如何让它把数字相加,然后从最高的10中减去,然后把两个数字的差值输出到我已经拥有的数字中?
谢谢Brad
发布于 2016-03-10 05:43:29
我相信这就是你要找的:
def take_away_from_nearest(number, nearest):
return nearest - (number % nearest)用法:
>>> take_away_from_nearest(53, 10)
7edit:如果我没理解错的话,这是完整的代码:
while True:
# this is just an easy way to keep asking until the input is correct
num = input("Please enter 7 numbers: ")
if len(num) == 7:
break
weird_sum = 0 #here's where we're gonna sum up the numbers; the "eighth number"
for index, character in enumerate(num):
if index % 2 == 0: # index is odd, so count the character thrice
print(3 * int(character))
weird_sum += 3 * int(character)
else: # index is even
print(int(character))
weird_sum += int(character)
print(10 - (weird_sum % 10)) # 10 minus (weird_sum modulo 10)
# and finally, adding them all up and checking whether it ends with 0:
print((10-(weird_sum % 10) + weird_sum) % 10 == 0) # prints True发布于 2016-03-10 05:51:50
如果你有一个数字,x,它等于53,那么向上应该是math.ceil(x),除了math.ceil()舍入1。为了说明这一点,我们除以10,使用math.ceil(),然后再乘以10:
import math
rounded_up = math.ceil(x / 10) * 10
result = rounded_up - x发布于 2016-03-10 06:02:32
布拉德,你能澄清一下你的问题吗?同样,上面的代码也不起作用。
第一行缺少括号,这不是有效的while length < 7 or length ? 7:
https://stackoverflow.com/questions/35903181
复制相似问题