gpt4 book ai didi

javascript - 闰年脚本,每次都返回 false

转载 作者:行者123 更新时间:2023-12-03 02:53:21 25 4
gpt4 key购买 nike

我正在编写一个代码来检查年份是否是闰年,但每次都返回 false。

<script src="dateLibrary.js"> </script>
<script>
function myLeapYearFunction(aDate)
{
var year = parseFloat(window.prompt("Enter a year: "));
var aDate = new Date(year);
document.write("is it leap? " + isLeapYear(aDate));
}
myLeapYearFunction();
</script>

日期库.js

function isLeapYear(aDate)
/*********************************************************************/
/* Argument is a Date object. Function returns the boolean value */
/* true if the year is a leap year. False otherwise, */
/*********************************************************************/

{
var year = aDate.getFullYear();
if (((year % 4) == 0) && ((year % 100)!=0) || ((year % 400) == 0))
return (true)
else
return (false)
};
/*************************End of function*****************************/

我已经尝试了 4 个小时,但找不到错误。

我非常感谢您的帮助。

最佳答案

不要使用Date对象,因为您只是测试年份而不是日期。

其他不相关的更改包括使用 parseInt 而不是 parseFloat,以及稍微重构您的 isLeapYear 函数。

function myLeapYearFunction() {
var year = parseInt(window.prompt("Enter a year: "));
console.log("is it leap? " + isLeapYear(year));
}

myLeapYearFunction();

function isLeapYear(year) {
var fourth = year % 4 == 0;
var hundredth = year % 100 == 0;
var fourHundredth = year % 400 == 0;
return fourth && (!hundredth || fourHundredth);
};

关于javascript - 闰年脚本,每次都返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47743254/

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