python - 我的输入不断读取为字符串而不是整数,我该如何解决这个问题

标签 python python-3.x

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。之后,显示最多 25 分硬币数、10 分硬币、5 分硬币和 1 便士数量。

例如,100 美元可以显示为 10000 便士、2 张 50 美元的钞票或 5 张 20 美元的钞票。但正确答案首先是100美元钞票的最大数量:1张百美元钞票。如果面额不为零,则仅显示面额金额。

我遇到的这个问题是我的输入不断读取为字符串而不是整数,我该如何解决这个问题

最佳答案

您可以在适当的情况下使用内置函数 int()float() 分别以 int 或 float 形式返回字符串。

例如:

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

金额设置为根据用户输入构造的 float 。

其他改进

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

Use // to divide and floor a number.

例如:

hundredDollar = amount // 100

将百元设置为整数,表示金额中 100 的最大次数。因此,如果金额为 150,则 HundredDollar 将设置为 1,因为该金额由一张整张百元钞票组成。

Use str() when concatenating a number with a string

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

str(hundredDollar) + " hundred dollar bills."

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

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

Add validation for user input

当接收来自用户的输入时,建议添加一些验证来检查用户输入的数据是否符合预期 - 在本例中,是有效的金额。这可以使用数据类型的 try except block 以及 if 语句来检查数据是否在有效范围内或满足附加要求。

关于python - 我的输入不断读取为字符串而不是整数,我该如何解决这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755481/

相关文章:

python - Django:如何在测试 View 时模拟文件上传

python - tf.where 导致优化器在 tensorflow 中失败

python - 如何在python中为列表的每个元素添加固定键?

python-3.x - 收集推文时如何修复 KeyError 'statuses'?

python - 无法从 python 3 中的输入文件中找到子字符串

python - 只在 python 中每第 5 个项目创建列表?

带有打开与显式打开和关闭的python

python-3.x - 从 Matplotlib 填充 Flask 图像

Python正则表达式获取两个字符串之间的文本

python - 在 python 模块中声明类