0

this is a simple program where I am getting input as change owed in $, and I have to return the total amount of coins. My program runs correctly until it comes down to counting pennies. Can someone see, Why does it give negative output, even when I told the program with an if statement not to run after it comes to 0.

import sys
import cs50


val = cs50.get_float(("Change owed: "))

count = 0
newVal = val

while newVal > .25:
        newVal = round(newVal - 0.25, 2)
        print(newVal)
        count +=1
        if newVal == 0.25:
          newVal = round(newVal - 0.25, 2)
          print(newVal)
          count +=1
        elif newVal < 0.25:
          newVal = round(newVal - 0.10, 2)
          print(newVal)
          count +=1
          if newVal < 0.10:
            newVal = round(newVal - 0.05, 2)
            print(newVal)
            count +=1
            if newVal < 0.05:
              newVal = round(newVal - 0.01, 2)
              print(newVal)
              count +=1
              if newVal < 0:
                break
              
              
print(count)

2 Answers2

1

Personally, I have no idea what your code is doing. Here's a version using division and mod. It's much more straightforward.

import sys
import cs50


val = cs50.get_float(("Change owed: "))

count = 0
newVal = int(val * 100)

if newVal >= 25:
    count += int(newVal / 25)
    newVal = newVal % 25

if newVal >= 10:
    count += int(newVal / 10)
    newVal = newVal % 10

if newVal >= 5:
    count += int(newVal / 5)
    newVal = newVal % 5

if newVal >= 1:
    count += int(newVal / 1)

print(count)
Bento Bot
  • 58
  • 1
  • 4
0

The issue you are having is that it's a floating point error. i.e.

>>> 0.03 - 0.01
0.019999999999999997

Perhaps it would be better if you made you multiplied the given value by 100, and so you'd be dealing with integer values instead of decimals.

On a different note:

you should probably divide instead of looping and subtracting, i.e.

coin_types = (25, 10, 5, 1)

def solution(value: int):
    coins = 0

    for coin in coin_types:
        coins += value // coin
        value = value % coin

        if value == 0:
            return coins

val = cs50.get_float(("Change owed: "))
print(solution(int(val*100)))
YousefZ01
  • 192
  • 2
  • 8