gpt4 book ai didi

javascript - 如果带有 ageDifference 的语句没有正确计算最接近的年龄

转载 作者:行者123 更新时间:2023-12-04 10:12:39 27 4
gpt4 key购买 nike

当我试图找到与 Sonya Sotomayor 年龄最接近的人时,出了点问题。谁能发现我的错误?

var notablePeople = {
"Elvis Presley": new Date(1935, 0, 8),
"Sonya Sotomayor": new Date(1954, 5, 25),
"Franklin D. Roosevelt": new Date(1882, 0, 30),
"Ben Carson": new Date(1951, 8, 18),
"Roger Staubach": new Date(1942, 1, 5),
"Steve Jobs": new Date(1955, 1, 24),
"Albert Einstein": new Date(1879, 2, 14),
"Isaac Asimov": new Date(1919, 9, 4),
"Jada Pinkett Smith": new Date(1971, 8, 18),
"Grace Hopper": new Date(1906, 11, 9),
"Jared Nicholas": new Date(1995, 5, 16)
};


// Find who is closest in age to Sonya Sotomayor
var sonyaAge = notablePeople["Sonya Sotomayor"].getTime();
var ageDifference = Infinity;
var personClosest = "";

for (person in notablePeople) {
// See if this person's age difference is closer
if (person != "Sonya Sotomayor" && Math.abs(notablePeople[person].getTime() - sonyaAge) < ageDifference) {
ageDifference = Math.abs(notablePeople[person].getTime() - sonyaAge);
ageDifference = ageDifference / 1000 / 60 / 60 / 24 / 365;

personClosest = person;
}
}

console.log("\nClosest age difference is " + person + " with " + ageDifference + " years difference.");



输出:
/*This is not correct
Closest age difference is Jared Nicholas with 19.473858447488585 years difference.
*/

最佳答案

var notablePeople = {
"Elvis Presley": new Date(1935, 0, 8),
"Sonya Sotomayor": new Date(1954, 5, 25),
"Franklin D. Roosevelt": new Date(1882, 0, 30),
"Ben Carson": new Date(1951, 8, 18),
"Roger Staubach": new Date(1942, 1, 5),
"Steve Jobs": new Date(1955, 1, 24),
"Albert Einstein": new Date(1879, 2, 14),
"Isaac Asimov": new Date(1919, 9, 4),
"Jada Pinkett Smith": new Date(1971, 8, 18),
"Grace Hopper": new Date(1906, 11, 9),
"Jared Nicholas": new Date(1995, 5, 16)
};


// Find who is closest in age to Sonya Sotomayor
var sonyaAge = notablePeople["Sonya Sotomayor"].getTime();
var ageDifference = Infinity;
var personClosest = "";

for (person in notablePeople) {
// See if this person's age difference is closer
console.log(person,Math.abs(notablePeople[person].getTime() - sonyaAge) / 1000 / 60 / 60 / 24 / 365);
if (person != "Sonya Sotomayor" && (Math.abs(notablePeople[person].getTime() - sonyaAge) < ageDifference)) {
ageDifference = Math.abs(notablePeople[person].getTime() - sonyaAge);
personClosest = person;
}
}
ageDifference = ageDifference / 1000 / 60 / 60 / 24 / 365;

console.log("\nClosest age difference is " + personClosest + " with " + ageDifference + " years difference.");

//您以错误的格式比较年龄,并且您使用的是person而不是personClosest

关于javascript - 如果带有 ageDifference 的语句没有正确计算最接近的年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61250824/

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