簡體   English   中英

帶用戶輸入的羅馬數字 Integer

[英]Roman Numeral to Integer with User Input

羅馬數字到 integer 轉換器與用戶輸入。 我在下面得到了這段代碼:

roman_numerals = {"I" : 1,
                  "V" : 5,
                  "X" : 10,
                  "L" : 50,
                  "C" : 100,
                  "D" : 500,
                  "M" : 1000
                  }

int_value = 0

user_input = input("Enter Roman Number: ").upper()

for i in range(len(user_input)):
    if user_input[i] in roman_numerals:
            if i + 1 < len(user_input) and roman_numerals[user_input[i]] < roman_numerals[user_input[i + 1]]:
                int_value -= roman_numerals[user_input[i]]
            else:
                int_value += roman_numerals[user_input[i]]
            print("The integer value is: ", int_value)
    else:
        print("Invalid input.")

問題是,它打印字符串“integer 值是:”與 len(user_input) 相同的計數,其中它應該只顯示該字符串的一行。 例如,用戶輸入“XIX”,十進制轉換為“19”,output 如下:

The integer value is: 10
The integer value is: 9
The integer value is: 19

我非常感謝您對它的反饋,因為我是 python 的新手,我想在其中成長和改進。

您必須將打印移出循環。 像這樣

roman_numerals = {"I" : 1,
                  "V" : 5,
                  "X" : 10,
                  "L" : 50,
                  "C" : 100,
                  "D" : 500,
                  "M" : 1000
                  }

int_value = 0

user_input = input("Enter Roman Number: ").upper()

for i in range(len(user_input)):
    if user_input[i] in roman_numerals:
        if i + 1 < len(user_input) and roman_numerals[user_input[i]] < roman_numerals[user_input[i + 1]]:
            int_value -= roman_numerals[user_input[i]]
        else:
            int_value += roman_numerals[user_input[i]]
    else:
        print("Invalid input.")
        quit()

print("The integer value is: ", int_value)

暫無
暫無

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

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