Python更改计算器变量位置

2024-09-27 00:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难弄清楚在哪里放置与每枚硬币相关的变量以及如何正确声明它们。
便士=1,四分之一=25

我需要对现有代码进行最少的更改,但需要找出如何使其工作

numPennies = int(input('Enter the number of pennies: '))
numNickels = int(input('Enter the number of nickels: '))
numDimes = int(input('Enter the number of dimes: '))
numQuarters = int(input('Enter the number of quarters: '))
totalCentValue = numPennies + numNickels + numDimes + numQuarters
totalDollars = totalCentValue / 100
if totalDollars < 100:
    print('Sorry, the amount you entered was more than one dollar.')

elif totalDollars > 100:
    print('Sorry, the amount you entered was less than one dollar.')

else:
    totalDollars == 100
    print('Congratulations!')
    print('The amount you entered was exactly one dollar!')
    print('You win the game!')

Tags: oftheyounumberinputamountoneint
2条回答

您只需要在使用它们之前创建它们。我想你在寻找类似的东西:

Penny, Nickel, Dime, Quarter = 1, 5, 10, 25
...
totalCentValue = numPennies * Penny + numNickels * Nickel + numDimes * Dime + numQuarters * Quarter

顺便说一下,您不想检查totalDollars < 100。你在找totalCents。总共1美元

以下内容可能会有所帮助,只是一些关于代码中看似不一致的建议。因为这显然是课堂作业(或者至少是教育性的),我将提供指导而不是直接的解决方案


totalCentValue = numPennies + numNickels + numDimes + numQuarters

这实际上是你拥有的硬币的数量,而不是那些硬币的价值。例如,一枚镍币值五美分,因此在计算中应作为numNickels * 5的因数。其他非便士硬币也是如此

您可以简单地乘以常量值,或设置名称以指示这些值(在计算之前)。这大概是:

numQuarters = int(input('Enter the number of quarters: '))

valPenny = 1      # Insert here, before use.
valNickel = 5
:
totalCentValue = numPennies * valPenny + numNickels * valNickel + ...

if totalDollars < 100:
    print('Sorry, the amount you entered was more than one dollar.')

一美元等于一百美分,因此您可能需要更改正在检查的变量或正在检查的常量。此外,<意味着它比一个值小,而不是多

这两点也适用于紧随其后的代码:

elif totalDollars > 100:
    print('Sorry, the amount you entered was less than one dollar.')

else:
    totalDollars == 100
    print('Congratulations!')
    print('The amount you entered was exactly one dollar!')
    print('You win the game!')

不确定为什么您觉得需要在此处更改totalDollars,但您还是将其设置为错误的值。总的美元价值是一美元而不是一百美元

相关问题 更多 >

    热门问题