亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將一個數除以百分比

將一個數除以百分比

呼喚遠方 2023-06-15 17:18:41
我有一個初始數字,比方說 3700,我想將它除以一個百分比。我有這段代碼:let available = 3700, percent = 10for (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 > 370Before deduction > 3700After deduction > 3330 Index: 1 | Use > 370   Before deduction > 3330After deduction > 2960 ...Index: 9 | Use > 370Before deduction > 370After deduction > 0它的工作原理是除以 10%,但是任何其他百分比數字都會顯示出意想不到的結果。有什么幫助嗎?
查看完整描述

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`)

}


查看完整回答
反對 回復 2023-06-15
?
躍然一笑

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`)

}


查看完整回答
反對 回復 2023-06-15
?
尚方寶劍之說

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`)

}


查看完整回答
反對 回復 2023-06-15
  • 3 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號