gpt4 book ai didi

javascript - 运行 Do...While 计算直到满足条件

转载 作者:行者123 更新时间:2023-12-04 00:50:43 24 4
gpt4 key购买 nike

我正在使用 Javascript 编写一个简单的 do...while 语句,目的是查看给定输入 num 的小数点长度,以及小数点的长度是否大于或等于到 1,获取 num 并将其添加到自身,直到十进制长度等于 0。目前,它适用于长度为 1 的小数,但任何更大的,它都会停止。

预期的输出,例如,当 num 为 8.75 时,应该是 35,而不是 17.5。

该系列应该需要 4 个步骤才能达到 35。

8.75

17.5

26.25

35

这是我的代码:

const num = 8.75;
var decimalLength = num.toString().split(".")[1].length;
let result = "";
let i = num;

do {
i = i + num;
result = result + num;
newLength = decimalLength;
} while (newLength < 0);

console.log(i);

最佳答案

您可以使用一些奇特的数学来获得不会一遍又一遍地循环的更明确的答案:

const num = 8.75;
var decimal = num % 1 //Decimal part
var decimalPlaces = num.toString().split(".")[1] ?.length || 0; //Get decimal places

//GCD function
const gcd = (x, y) => (!y ? x : gcd(y, x % y));

//GCD between decimal and 1, need to make it whole number to get multiplier, so multiply each with 10^[decimal places]
//Get what's remaining when divided by 10^[decimal places] as well, to see what to multiply by to get whole number
var multiplier = 10 ** decimalPlaces / gcd(10 ** decimalPlaces, decimal * 10 ** decimalPlaces)

//Use log change of base property to get value in power of 2
var outputExponent = Math.log(multiplier) / Math.log(2)
//Multiply number by multiplier
var outputValue = num * multiplier

console.log(outputExponent) //Power of 2 to multiply by to get whole number
console.log(outputValue) //The whole number itself

关于javascript - 运行 Do...While 计算直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66786036/

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