3 回答

TA貢獻1883條經驗 獲得超3個贊
重要變化:修改了三元運算并更改了循環測試
請參閱下面的工作代碼:
let available = 3700, percent = 20
for (let index = 0; index < 100/percent; index++) {
let use = index == 0 ? (percent / 100) * available : available / (100/percent - index)
console.log(`Index: ${index} | Use > ${use}`)
console.log(`Before reduction > ${available}`)
available -= use
console.log(`After reduction > ${available}\n`)
}

TA貢獻1826條經驗 獲得超6個贊
在定義使用時去掉條件。這應該解決它。
let available = 3700, percent = 10
let availableBeginning = available
for (let index = 0; available > 0 ; index++) {
let use = percent / 100) * availableBeginning
console.log(`Index: ${index} | Use > ${use}`)
console.log(`Before reduction > ${available}`)
available -= use
console.log(`After reduction > ${available}\n`)
}

TA貢獻1788條經驗 獲得超4個贊
這將適用于您的情況。我不確定為什么你有 `available / ((percent - index) % percent)),這基本上只是將你的原始數字除以你想要扣除的百分比,然后取模原始百分比。因此,在這種情況下,在 0 之后,您的行為是 use = 878.75,因為您將 3515 除以 (5 - 1) % 5,即 = 4. 3515 / 4 = 878.85。這將扣除得相當快,因為您每次迭代至少將 1 / 百分比值作為已扣除數字的整數。
事實證明,你的使用邏輯實際上是沒有意義的,如果你想每次迭代都扣除偶數,你不必根據任何邏輯設置它......只需重復計算和扣除多少次你想要的.
無論如何,這是解決方案:
let available = 3700, percent = 5;
// This is going to be the constant deduction you will continue to use
let deduction = 3700 * (percent / 100);
for (let index = 0; index < 10; index++) {
console.log(`Index: ${index} | Use > ${deduction}`)
console.log(`Before deduction > ${available}`)
available -= deduction
console.log(`After deduction > ${available}\n`)
}
添加回答
舉報