Hello!
I’m going through the Go track and this is the most fun I’ve had learning to code so far. But, I’m halted by a single test in the Interest is Interesting exercise: FAIL: TestYearsBeforeDesiredBalance/Result_balance_would_be_exactly_same_as_target
: Want 2, got 3.
Now, I have checked my code, I have checked the community solutions, as far as I’m concerned it should just work™. Yet here I am. If any fresh pairs of eyes could take a look and tell me the error of my ways I’d be grateful.
Here is the code below:
package interest
const BelowZero, ToThousand, ToFiveThousand, AboveFiveThousand float64 = 3.213, 0.5, 1.621, 2.475
// InterestRate returns the interest rate for the provided balance.
func InterestRate(balance float64) float32 {
if balance < 0 {
return float32(BelowZero)
} else if balance >= 0 && balance < 1000 {
return float32(ToThousand)
} else if balance >= 1000 && balance < 5000 {
return float32(ToFiveThousand)
} else {
return float32(AboveFiveThousand)
}
}
// Interest calculates the interest for the provided balance.
func Interest(balance float64) float64 {
var interest float64
if balance < 0 {
interest = balance * (BelowZero / 100.0)
} else if balance >= 0 && balance < 1000 {
interest = balance * (ToThousand / 100.0)
} else if balance >= 1000 && balance < 5000 {
interest = balance * (ToFiveThousand / 100.0)
} else {
interest = balance * (AboveFiveThousand / 100.0)
}
return interest
}
// AnnualBalanceUpdate calculates the annual balance update, taking into account the interest rate.
func AnnualBalanceUpdate(balance float64) float64 {
var newBalance float64
if balance < 0 {
newBalance = balance + Interest(balance)
} else if balance >= 0 && balance < 1000 {
newBalance = balance + Interest(balance)
} else if balance >= 1000 && balance < 5000 {
newBalance = balance + Interest(balance)
} else {
newBalance = balance + Interest(balance)
}
return newBalance
}
// YearsBeforeDesiredBalance calculates the minimum number of years required to reach the desired balance.
func YearsBeforeDesiredBalance(balance, targetBalance float64) int {
years := 0
for balance < targetBalance {
balance = AnnualBalanceUpdate(balance)
years++
}
return years
}
Cheers!