gpt4 book ai didi

javascript - 使用 JavaScript/jQuery 的杯子分数

转载 作者:行者123 更新时间:2023-11-30 20:09:09 26 4
gpt4 key购买 nike

假设 1 杯等于 2.36 dl。我想要一个函数,它可以在 dl 中输入代表杯子的小数,并将杯子的数量输出为分数。

到目前为止,这是我得到的结果:

  var dl = 2.36;

cupToFraction(.78); // 1/3 cup
cupToFraction(2.36); // 1 cup
cupToFraction(4.72); // 2 cups
cupToFraction(8.26); // 3 1/2 cups

function cupToFraction (cup) {
var deci = (cup / dl);
alert(deci);
}

最佳答案

一种选择是使用连分数来获得有理近似值:

var dl = 2.36;
function cupToFraction (cup) {
var deci = (cup / dl);
var integerPart = Math.floor(deci);
deci -= integerPart;
deci = 1 / deci;
var c = [];
// Tune these parameters for how far you want the continued fraction to go
// 3 means at most 3 terms; 10 means no terms higher than 10.
for (let i = 0; i < 3 && deci < 10; ++i) {
let f = Math.floor(deci);
c.push(f);
deci -= f;
deci = 1/deci;
}
if (c.length === 0) return [integerPart, 0, 1];
var p = 1, q = c.pop();
while (c.length > 0) {
var int = c.pop();
p = q*int + p;
[p, q] = [q, p];
}
// Handle case like cupToFraction(2.35)
if (p === q) { p = 0; integerPart++; }
return [integerPart, p, q];
}

它返回一个数组,其元素是integerPart, numerator, denominator。例如,cupToFraction(8.26) 给出 [3, 1, 2] for 3 1/2。我确信这个算法可以更优化,但现在必须这样做。

关于javascript - 使用 JavaScript/jQuery 的杯子分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52581818/

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