从最近的10

2024-04-26 07:18:38 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我已经编写了代码,用户可以输入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中去掉,然后把两者的差值输出到我已经有的数字中呢?你知道吗

谢谢 布拉德


Tags: 代码用户inputstringlen数字lengthnum
3条回答

我相信这就是你想要的:

def take_away_from_nearest(number, nearest):
    return nearest - (number % nearest)

用法:

>>> take_away_from_nearest(53, 10)
7

编辑: 如果我理解正确,这就是全部代码:

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

如果你有一个数字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

布拉德,你能澄清一下你的问题吗?此外,您的上述代码不工作。你知道吗

第一行缺少括号,这是无效的while length < 7 or length ? 7:

相关问题 更多 >