首页 文章

硬币改变制造商Python程序

提问于
浏览
1

我是初学者编程课程 . 我们必须做一个改变制造者计划的练习 . 输入必须在0-99之间,并且当输入在四者之间分配时,必须以四分之一,硬币,镍币和便士表示 . 我编写了一个涉及循环和whiles的代码,但他想要更简单的代码和更小的代码 . 他给了我这个帮助我的方法:

c=int(input('Please enter an amount between 0-99:'))
print(c//25)
print(c%25)

他告诉我们,这基本上就是我们所需要的,只需要添加硬币,镍币和硬币 . 我用硬币,镍币和硬币尝试多种方式,但我无法正确输出 . 每当我输入'99'时,我得到3分为四分之一,2分为硬币,1分为镍,0分为便士 . 如果有人能够帮助我,那将是美好的!

3 回答

  • 3

    我现在肯定你想要实现的目标 . 使用模数运算符,您可以轻松找出多少个季度,硬币,镍币和便士 .

    我们只说你输入99 .

    c=int(input('Please enter an amount between 0-99:'))
    print(c//25, "quarters")
    c = c%25
    print(c//10, "dimes")
    c = c%10
    print(c//5, "nickles")
    c = c%5
    print(c//1, "pennies")
    

    这会打印出来:

    3 quarters
    2 dimes
    0 nickles
    4 pennies
    
  • 1

    实际的诀窍是知道因为每枚硬币的 Value 至少是下一个较小面额的两倍,you can use a greedy algorithm . 其余的只是实现细节 .

    在这里's a slightly DRY' er(但可能,呃,更令人困惑)实现 . 所有我真正做的不同的是使用列表来存储我的结果,并利用tuple unpackingdivmod . 此外,这在将来更容易扩展:我需要做的就是支持1美元账单是将 coins 更改为 [100, 25, 10, 5, 1] . 等等 .

    coins = [25,10,5,1] #values of possible coins, in descending order
    results = [0]*len(coins) #doing this and not appends to make tuple unpacking work
    initial_change = int(input('Change to make: ')) #use raw_input for python2
    remaining_change = initial_change
    for index, coin in enumerate(coins):
        results[index], remaining_change = divmod(remaining_change, coin)
    print("In order to make change for %d cents:" % initial_change)
    for amount, coin in zip(results, coins):
        print("    %d %d cent piece(s)" % (amount, coin))
    

    给你:

    Change to make: 99
    In order to make change for 99 cents:
        3 25 cent piece(s)
        2 10 cent piece(s)
        0 5 cent piece(s)
        4 1 cent piece(s)
    
  • 2
    n = int(input("Enter a number between 0-99"))
    q = n // 25
    n %= 25
    d = n // 10
    n %= 10
    ni =  n // 5
    n %= 5
    c = n % 5
    print(str(q) +" " + str(d) +" " + str(ni) + " " + str(c))
    

    我希望这有帮助?像这样的东西,但不要只是复制它 . 每次除以25 10 5你必须丢失那部分,因为它已经被计算在内 . 最后打印出你想要的东西:) .

相关问题