将一个数除以百分比

我有一个初始数字,比方说 3700,我想将它除以一个百分比。我有这段代码:


let available = 3700, percent = 10


for (let index = 0; index < 10; index++) {

    let use = index == 0 ? (percent / 100) * available : available / ((percent - index) % percent)


    console.log(`Index: ${index} | Use > ${use}`)


    console.log(`Before reduction > ${available}`)

    available -= use

    console.log(`After reduction > ${available}\n`)

}

Index: 0 | Use > 370

Before deduction > 3700

After deduction > 3330 


Index: 1 | Use > 370   

Before deduction > 3330

After deduction > 2960 


...


Index: 9 | Use > 370

Before deduction > 370

After deduction > 0

它的工作原理是除以 10%,但是任何其他百分比数字都会显示出意想不到的结果。


有什么帮助吗?


呼唤远方
浏览 144回答 3
3回答

白板的微信

重要变化:修改了三元运算并更改了循环测试请参阅下面的工作代码:let available = 3700, percent = 20for (let index = 0; index < 100/percent; index++) {&nbsp; &nbsp; let use = index == 0 ? (percent / 100) * available : available / (100/percent - index)&nbsp; &nbsp; console.log(`Index: ${index} | Use > ${use}`)&nbsp; &nbsp; console.log(`Before reduction > ${available}`)&nbsp; &nbsp; available -= use&nbsp; &nbsp; console.log(`After reduction > ${available}\n`)}

跃然一笑

在定义使用时去掉条件。这应该解决它。let available = 3700, percent = 10let availableBeginning = availablefor (let index = 0; available > 0 ; index++) {&nbsp; &nbsp; let use = percent / 100) * availableBeginning&nbsp; &nbsp; &nbsp;console.log(`Index: ${index} | Use > ${use}`)&nbsp; &nbsp; &nbsp;console.log(`Before reduction > ${available}`)&nbsp; &nbsp; &nbsp;available -= use&nbsp; &nbsp; &nbsp;console.log(`After reduction > ${available}\n`)}

尚方宝剑之说

这将适用于您的情况。我不确定为什么你有 `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 uselet deduction = 3700 * (percent / 100);for (let index = 0; index < 10; index++) {&nbsp; &nbsp; console.log(`Index: ${index} | Use > ${deduction}`)&nbsp; &nbsp; console.log(`Before deduction > ${available}`)&nbsp; &nbsp; available -= deduction&nbsp; &nbsp; console.log(`After deduction > ${available}\n`)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript