每天翻倍的金额,需要将便士数转换为美元+美分



这个程序从1美分开始,每天翻倍。但是,我一直在尝试找到一种方法将便士的数量转换为一美元和美分的数量。例如,将 1020 便士转换为 10.20 美元。

我也在尝试这样做,如果用户输入不是正数,用户将不断被提示,直到他们输入正数。但是,这是行不通的。

我也觉得我使用范围搞砸了,因为我想输入设定的天数,比如 16 天,当我输入 16 天时,我收到 1-17 天,因为范围应该这样做,我不确定如何解决这个问题。

b = int(input("Input number of days "))
if b > 0:
print(b)
else:
b = int(input("Days must be positive "))

print("Day 1:","1")
days = 1
aIncrement = 2 
penny = 1

for i in range(b):
pAmount = int(penny*2) 
addAmount = int(2**aIncrement -1) 
aIncrement +=1
days +=1
penny *= 2 
print("Day " + str(days) + ":",pAmount)

您的问题有多个部分,这对于堆栈溢出来说并不理想,但我会尝试全部解决。

修复数值以显示美元和美分。

正如在其他答案的注释中所指出的,由于浮点符号,除法经常会遇到障碍。但是在这种情况下,由于我们真正关心的只是 100 进入便士计数的次数和余数,我们可能可以安全地使用 Python 中包含的divmod()并计算一个数字可整除在另一个数字中的次数和整数的余数。

为清楚起见,divmod()返回一个tuple,在下面的示例中,我解压缩了元组中存储的两个值,并将每个单独的值分配给两个变量之一:dollarscents

dollars, cents = divmod(pAmount, 100)           # unpack values (ints)
# from divmod() function
output = '$' + str(dollars) + '.' + str(cents)  # create a string from
# each int

修复范围问题

range()函数生成一个数字,您可以将其设置为在您想要的位置开始和结束,请记住,结束数字必须设置为比您想要去的值高一个值......即要获得从 1 到 10 的数字,您必须使用 1 到 11 的范围。在代码中,使用i作为占位符,并单独使用days来跟踪当天的值。由于您的用户会告诉您他们想要b天,因此您需要立即增加该值。我建议将这些结合起来以简化事情,并可能使用稍微多一点的自我记录变量名称。另外需要注意的是,由于这从第一天开始,我们可以删除一些用于在循环开始前手动处理第一天的设置代码(更多内容将在后面的部分中介绍)。

days = int(input("Input number of days "))   
for day in range(1, days + 1):
# anywhere in your code, you can now refer to day
# and it will be able to tell you the current day

连续输入

如果我们要求用户提供初始输入,他们可以输入:

  • 负数
  • 正数

因此,我们的while循环应该检查任何非阳性条件(即days <= 0)。如果第一个请求是正数,则 while 循环实际上被完全跳过,脚本继续,否则它会不断请求额外的输入。通知。。。我在第二个input()函数中编辑了字符串,向用户显示问题并告诉他们下一步该怎么做。

days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input positive number of days: "))     

将所有这些放在一起,代码可能如下所示:

我将上面的项目放在一起并清理了一些其他东西。

days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input number of days: "))
# aIncrement = 2        # this line not needed
penny = 1
for day in range(1, days + 1):
pAmount = int(penny)                      # this line was cleaned up
# because we don't need to manually
# handle day one
dollars, cents = divmod(pAmount, 100)
output = '$' + str(dollars) + '.' + str(cents)
# addAmount = int(2**aIncrement -1)    # this line not needed
# aIncrement +=1                       # this line not needed
penny *= 2 
print("Day " + str(day) + ":", output)

对于连续提示,可以使用 while 循环。

while True:
user_input = int(input("Enter the number"))
if user_input > 0:
break
else:
continue

或者:

user_input = int(input("Enter the number"))
while user_input <= 0:
user_input = int(input("Enter the number"))

对于范围问题,您可以将 -1 添加到要传递范围的参数中。

for i in range(b - 1):

最新更新