gpt4 book ai didi

javascript - 函数没有给出响应

转载 作者:行者123 更新时间:2023-12-02 21:46:05 24 4
gpt4 key购买 nike

这是我的代码:

function findTriad(numbers, sum) {
for (let i = 0; i < numbers.length - 1; i++) {
const firstNumber = numbers[i];
const newSum = sum - firstNumber;
let startOfCheckIndex = i + 1;
const endOfCheckIndex = numbers.length - 1;

while (startOfCheckIndex < endOfCheckIndex) {
const possibleAnswer =
numbers[startOfCheckIndex] + numbers[endOfCheckIndex];
if (possibleAnswer === newSum) {
return [
numbers[i],
numbers[startOfCheckIndex],
numbers[endOfCheckIndex]
];
} else if (sum < newSum) {
startOfCheckIndex++;
}
}
}
return ["N/A"];
}

function logFindTriad(numbers, sum) {
const answer = findTriad(numbers, sum);

console.log("Sum required: " + sum);
console.log("Numbers given: " + numbers.join(", "));
console.log("Found: " + answer.join(", ") + "\n");
}

logFindTriad([10, 15, 3, 7], 20);

有谁知道为什么这段代码没有给我任何值(value)?如果您发现我的代码有任何错误或需要改进的地方,它应该给我返回 [10,3,7],请告诉我,即使它不能解决问题。

最佳答案

代码第一次输入while (startOfCheckIndex < endOfCheckIndex) {startOfCheckIndex 为 1,endOfCheckIndex 为 3这意味着possibleAnswer是 10 + 7 = 17。newSum 为 10,sum 为 20这意味着两者都没有

if (possibleAnswer === newSum) {

} else if (sum < newSum) {

是真的。导致 startOfCheckIndex 永远不会改变。

反过来,while (startOfCheckIndex < endOfCheckIndex) {永远为真,导致无限循环。

您需要添加 else条款或其他一些离职条件。

这是一个演示该问题的示例。

let loopRestriction = 100

function findTriad(numbers, sum) {
for (let i = 0; i < numbers.length - 1; i++) {
const firstNumber = numbers[i];
const newSum = sum - firstNumber;
let startOfCheckIndex = i + 1;
const endOfCheckIndex = numbers.length - 1;

while (startOfCheckIndex < endOfCheckIndex) {

const possibleAnswer = numbers[startOfCheckIndex] + numbers[endOfCheckIndex];
if (loopRestriction-- <= 0) {
console.log("Stuck in while loop for atleast 100 iterations.")
break
}
console.log({
startOfCheckIndex,
endOfCheckIndex,
possibleAnswer,
sum,
newSum
})

if (possibleAnswer === newSum) {
return [
numbers[i],
numbers[startOfCheckIndex],
numbers[endOfCheckIndex]
];
} else if (sum < newSum) {
startOfCheckIndex++;
}
}
}
return ["N/A"];
}

function logFindTriad(numbers, sum) {
const answer = findTriad(numbers, sum);

console.log("Sum required: " + sum);
console.log("Numbers given: " + numbers.join(", "));
console.log("Found: " + answer.join(", ") + "\n");
}

logFindTriad([10, 15, 3, 7], 20);

关于javascript - 函数没有给出响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60245182/

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