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

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

JavaScript:添加高達 100 % 的四舍五入百分比

JavaScript:添加高達 100 % 的四舍五入百分比

富國滬深 2023-07-14 15:09:40
我正在尋找paxdiablo中該算法的最短、最快的純 JavaScript 實現,以將舍入百分比添加到 100%。Value? ? ? CumulValue? CumulRounded? PrevBaseline? Need---------? ----------? ------------? ------------? ----? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 013.626332? ?13.626332? ? ? ? ? ? 14? ? ? ? ? ? ?0? ? 14 ( 14 -? 0)47.989636? ?61.615968? ? ? ? ? ? 62? ? ? ? ? ? 14? ? 48 ( 62 - 14)?9.596008? ?71.211976? ? ? ? ? ? 71? ? ? ? ? ? 62? ? ?9 ( 71 - 62)28.788024? 100.000000? ? ? ? ? ?100? ? ? ? ? ? 71? ? 29 (100 - 71)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ---? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 100
查看完整描述

2 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

const values = [13.626332, 47.989636, 9.596008 , 28.788024];


const round_to_100 = (arr) => {

    let output = [];

    let acc = 0;


    for(let i = 0; i < arr.length; i++) {

        let roundedCur = Math.round(arr[i]);

        const currentAcc = acc;

        if (acc == 0) {

            output.push(roundedCur);

            acc += arr[i];

            continue;

        }

        acc += arr[i];

        output.push(Math.round(acc) - Math.round(currentAcc));

    }


    return output;

}


console.log(round_to_100(values));

我的基準和唯一的其他答案 dshung 使用 benchmark.js 的 bar 函數


mine x 17,835,852 ops/sec ±5.13% (80 runs sampled)

theirs x 1,785,401 ops/sec ±4.57% (84 runs sampled)

Fastest is mine


查看完整回答
反對 回復 2023-07-14
?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

剛剛翻譯了接受的答案中所做的事情


const bar = (numbers) => {

    const expectedSum = 100;


    const sum = numbers.reduce((acc, n) => acc + Math.round(n), 0);

    const offset = expectedSum - sum;


    numbers.sort((a, b) => (Math.round(a) - a) - (Math.round(b) - b));


    return numbers.map((n, i) => Math.round(n) + (offset > i) - (i >= (numbers.length + offset)));

}


查看完整回答
反對 回復 2023-07-14
  • 2 回答
  • 0 關注
  • 214 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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