簡體   English   中英

將兩位數加在一起作為兩個單獨的數字

[英]adding together double digit numbers as two individual digits

我讓用戶輸入他們的“信用卡號”(11 個數字)並將其分配給變量 card_number。 然后我使用 card_number.split() 函數將輸入轉換為列表並將其分配給變量 card_numbers。

然后我想遍歷數字列表,從最右邊的數字開始,向左移動,每第二個數字翻一番。 如果每第二個數字加倍的乘積大於 9(例如 7 * 2 = 14),那么我會將乘積的數字相加(1 + 4 = 5)。 如果一位數的乘積小於 10,我將保持原樣。 到目前為止,這是我的代碼:

card_number = input('Please enter your 11 digit card number: ')
card_numbers = card_number.split()

list1 = []

total = 0 

for num in card_numbers[-2:0:-2]:
    num = int(num) * 2
    if num >= 10:
        list1.append(num)
        
    if num < 10:
        total = total + num
    

print(total)
print(list1)

我的問題是,如果將一個數加倍的乘積 > 10,例如 7 * 2 = 14,我如何將 1 和 4 相加?

只需單獨拉出數字即可。

    if num > 9:
        total += num//10 + num % 10

您不必聲明變量card_numbers因為輸入變量中沒有空格。 這應該工作

card_number = input('Please enter your 11 digit card number: ')
#card_numbers = card_number.split()
list1 = []

total = 0 

for num in card_number[-2:0:-2]:
    num = int(num) * 2
    if num >= 10:
        list1.append(num)
        total += num//10 + num%10
        
    if num < 10:
        list1.append(num)
        total = total + num
    

print(total)
print(list1)

您不能使用split() ,因為它沒有被空格或任何其他字符分隔,將卡號轉換為列表或直接將其切片都將同樣工作:

同樣在您的代碼中:

如果 num >= 10:list1.append(num) 如果 num < 10:total = total + num

您的要求與您編寫的代碼完全相反:

如果每第二個數字加倍的乘積大於 9(例如 7 * 2 = 14),那么我會將乘積的數字相加(1 + 4 = 5)。 如果一位數的乘積小於 10,我將保持原樣。

我已經重寫了代碼,您可以看到它在每個循環中選擇的值,您可以隨心所欲,希望它有助於找到滿足您需求的解決方案:

card_number = input('Please enter your 11 digit card number: ')
card_numbers = list(card_number)
print(card_numbers)
list1 = []

temp = 0 

for num in card_numbers[-2:0:-2]:
    double_num = int(num) * 2
    
    if double_num >= 10:
        # finding each each digit in the 2 digit number and summing up each digit
        total = double_num//10+double_num%10
        
    if double_num < 10:

        temp=double_num
    # checking each value 
    print(num,"",double_num," ",total," ",temp)
    # Reseting the value to 0
    total=0
    temp=

上面的輸出是:

Please enter your 11 digit card number: 123456789
['1', '2', '3', '4', '5', '6', '7', '8', '9']
8  16   7   0
6  12   3   0
4  8   3   8
2  4   3   4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM