[英]Taking away from nearest 10
好的,我已經編寫了代碼,以便用戶可以輸入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個,這就是我的數字八個數字,然后在我得到該數字后將其打印出來,如何將其加起來並從最高的10個中帶走,並將兩者的差輸出到我已經擁有的數字中?
謝謝布拉德
我相信這就是您要尋找的:
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()
四舍五入為1
之外,向上的應該是math.ceil(x)
。 為了解決這個問題,我們將其除以10,使用math.ceil()
,然后再乘以10:
import math
rounded_up = math.ceil(x / 10) * 10
result = rounded_up - x
布拉德,你能澄清你的問題嗎? 您的上述代碼也不起作用。
在第一行缺少括號, while length < 7 or length ? 7:
while length < 7 or length ? 7:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.