I am trying to finish an assignment and am very close by python is always rounding my answer down instead of up when it's supposed to. Here is my code:
startingValue = int(input())
RATE = float(input()) /100
TARGET = int(input())
currentValue = startingValue
years = 1
print("Year 0:",'$%s'%(str(int(startingValue)).strip() ))
while years <= TARGET :
interest = currentValue * RATE
currentValue += interest
print ("Year %s:"%(str(years)),'$%s'%(str(int(currentValue)).strip()))
years += 1
Here is what my code outputs: Year 0: $10000, Year 1: $10500, Year 2: $11025, Year 3: $11576, Year 4: $12155, Year 5: $12762, Year 6: $13400, Year 7: $14071, Year 8: $14774, Year 9: $15513,
Here is what is supposed to output: Year 0: $10000, Year 1: $10500, Year 2: $11025, Year 3: $11576, Year 4: $12155, Year 5: $12763, Year 6: $13401, Year 7: $14071, Year 8: $14775, Year 9: $15514,
I need them to match, AKA round up. Someone please help me :(
In Python the int() constuctor will always round down, eg
>>> int(1.7)
1
https://docs.python.org/2/library/functions.html#int
If x is floating point, the conversion truncates towards zero.
If you want to always round up, you need to:
>>> import math
>>> int(math.ceil(1.7))
2
or rounded to nearest:
>>> int(round(1.7))
2
>>> int(round(1.3))
1
(see https://docs.python.org/2/library/functions.html#round ...this builtin returns a float)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With