gpt4 book ai didi

javascript - 使用 for 循环将数字插入数组。 (求给定数的GCF)

转载 作者:行者123 更新时间:2023-12-01 02:22:15 25 4
gpt4 key购买 nike

我正在尝试查找我传递到函数中的任何数字的 GCF。当我向存储阵列发出警报时,我得到的只是 0。

为什么我的存储数组中唯一的值是 0?即使循环运行了 12 次,为什么我的值没有被推送到存储数组中?

let gcf = num => {
let storage = [];
for (let i = 0; i <= num; i++) {
// if it divides evenly into num, it is a factor and we want to push it
// into an array
if (i % num == 0) {
storage.push(i);
} else {
continue;
}
}
// will sort the array from highest to lowest
storage = storage.sort((a, b) => {
return b - a;
})
alert(storage[0]);
// and return storage[0] for the gcf
}

gcf(12);

最佳答案

你的模运算符是倒退的;)

let gcf = num => {
let storage = [];
for (let i = 0; i <= num; i++) {
// if it divides evenly into num, it is a factor and we want to push it
// into an array
if (num % i == 0) {
storage.push(i);
} else {
continue;
}
}
// will sort the array from highest to lowest
storage = storage.sort((a, b) => {
return a - b;
})
alert(storage[0]);
// and return storage[0] for the gcf
}

gcf(12);

关于javascript - 使用 for 循环将数字插入数组。 (求给定数的GCF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120014/

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