首页 文章

我的输入继续作为字符串而不是int读取如何解决此问题

提问于
浏览
2
amount = input  ("enter amount: ")

hundredDollar = amount / 100
amount = amount % 100

fiftyDollar = amount / 50
amount = amount % 50

twentyDollar = amount / 20
amount = amount % 20

tenDollar = amount / 10
amount = amount % 10

fiveDollar = amount / 5
amount = amount % 5

oneDollar = amount / 1
amount = amount % 1

quarter = amount / .25
amount = amount % .25

dime = amount / .10
amount = amount % .10

nickel = amount / .05
amount = amount % .05

penny = amount / .01
amount = amount % .01

print(int(hundredDollar) + " hundred dollar bills")
print(int(fiftyDollar) + " fifty dollar bills")
print(int(twentyDollar) + " twenty dollar bills")
print(int(tenDollar) + " ten dollar bills")
print(int(fiveDollar) + " five dollar bils")
print(int(oneDollar) + " one dollar bills")
print(int(quarter) + " quarters")
print(int(dime) + " dimes ")
print(int(nickel) + " nickels")
print(int(penny) + " pennies")

所以这个程序的目标是输出最大数量的美元钞票,其中包含数量,然后是最大数百,五十,美元钞票,然后是20,然后是10,5和1.之后,显示最大数量四分之一,硬币,镍币和硬币 .

例如,100美元可以显示为10000便士,或2个五十美元的钞票或5个二十美元的钞票 . 但正确答案是首先100美元钞票的最大数量:1百美元的钞票 . 如果面值不为零,则仅显示面额 .

我遇到的这个问题是我的输入继续读取字符串而不是int如何解决这个问题

3 回答

  • 0

    您可以使用内置函数 int()float() 将字符串分别作为int或float返回,并在适当的位置返回 .

    例如:

    amount = float(input("Enter amount:"))
    

    将金额设置为从用户输入构造的浮点数 .

    Other Improvements

    查看您提供的代码,您可以进行的其他改进如下:

    使用//来划分和排列数字 .

    例如:

    hundredDollar = amount // 100
    

    将hundredDollar设置为一个整数,表示100进入量的最大次数 . 因此,如果金额为150,则数百将被设置为1,因为金额由一整百美元的账单组成 .

    将数字与字符串连接时使用str()

    当您将数字与字符串连接(组合)并且数字首先出现时,您需要先将数字转换为字符串 . 例如:

    str(hundredDollar) + " hundred dollar bills."
    

    当使用float并且您希望输出显示为int,即2而不是2.0时,您可以使用int()函数或格式化输出 . 例如:

    print( int(hundredDollar), "hundred dollar bills." )
    

    为用户输入添加验证

    当从用户接收输入时,建议添加一些验证以检查用户输入的数据是否符合预期 - 在这种情况下,是有效金额 . 这可以使用数据类型的 tryexcept 块以及 if 语句来检查数据是否在有效范围内或满足其他要求 .

  • 1

    你的输入继续作为 str 而不是 int 阅读的原因是因为 input() 返回一个字符串对象(自从他们从Python 2中删除了 raw_input() 函数并使 input() 函数取代它之后就是如此) .

    使用 int() 函数将字符串更改为整数,如下所示:

    amount = int(input("Enter amount: "))
    

    (这也适用于 float() 函数 . )

    但是,如果用户输入字符串,则会产生错误 . 要避免这种情况,请将转换包装到 try ... except 块中的整数:

    try:
      amount = int(input("Enter amount: "))
    except ValueError:
      #Perhaps prompt the user to try again here
    

    (再一次,这将适用于 float() 函数)

  • 4

    用这个

    amount = eval(input  ("enter amount: "))
    

    它将字符串从输入转换为int

    如果你想漂浮

    amount = float(input  ("enter amount: "))
    

相关问题