gpt4 book ai didi

ruby - "Buying a car" ruby 代码 war

转载 作者:数据小太阳 更新时间:2023-10-29 07:51:46 24 4
gpt4 key购买 nike

我正在尝试进行 Ruby codewars 挑战,但由于我通过了示例测试但无法通过最终测试,因此陷入困境。我收到错误预期:[8, 597],而不是:[8, 563]。

Instructions :

A man has a rather old car being worth $2000. He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one.

He thinks he can save $1000 each month but the prices of his old car and of the new one decrease of 1.5 percent per month. Furthermore the percent of loss increases by a fixed 0.5 percent at the end of every two months.

Example of percents lost per month:

If, for example, at the end of first month the percent of loss is 1, end of second month percent of loss is 1.5, end of third month still 1.5, end of 4th month 2 and so on ...

Can you help him? Our man finds it difficult to make all these calculations.

How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over?

def nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth)
months = 0
leftover = 0
currentSavings = 0
until (currentSavings + startPriceOld) >= (startPriceNew)
months += 1
months.even? ? percentLossByMonth = percentLossByMonth + 0.5 : percentLossByMonth
startPriceNew = startPriceNew * (1 - (percentLossByMonth/100))
startPriceOld = startPriceOld * (1 - (percentLossByMonth/100))
currentSavings = currentSavings + savingperMonth
end
leftover = currentSavings + startPriceOld - startPriceNew
return [months, leftover.abs.to_i]
end

我不想查看解决方案,我也不需要这里的解决方案,只要向正确的方向插入就会非常有帮助。

另外,我知道代码在很多方面可能都不是最优的,但我 2 周前开始编码,所以尽我所能。

Tnx 伙计们

最佳答案

你的算法很好。但是你有两个编码错误:

1) percentLossByMonth 在除以 100 之前需要转换为 float (5/100 = 0 而 (5.to_f)/100 = 0.05)

2) 说明中说需要返回最接近剩余的整数,即leftover.round

def nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth)
months = 0
leftover = 0
currentSavings = 0
until (currentSavings + startPriceOld) >= (startPriceNew)
months += 1
percentLossByMonth += months.even? ? 0.5 : 0
startPriceNew = startPriceNew * (1 - (percentLossByMonth.to_f/100))
startPriceOld = startPriceOld * (1 - (percentLossByMonth.to_f/100))
currentSavings += savingperMonth
end
leftover = currentSavings + startPriceOld - startPriceNew
return [months, leftover.round]
end

关于ruby - "Buying a car" ruby 代码 war ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44556719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com