gpt4 book ai didi

javascript - 闰年功能;这个解决方案如何运作?

转载 作者:行者123 更新时间:2023-11-28 11:44:56 25 4
gpt4 key购买 nike

问题是这样的:

给定年份,报告是否为闰年。

这里棘手的事情是公历中的闰年发生:

on every year that is evenly divisible by 4
except every year that is evenly divisible by 100
unless the year is also evenly divisible by 400

我的解决方案(有效)是这样的:

export const isLeap = (year) => {
const yearModFour = (year % 4) === 0
const yearModHundred = (year % 100) === 0
const yearModFourHundred = (year % 400) === 0
const isLeapYear = yearModFour === yearModHundred === yearModFourHundred
return isLeapYear
}

我得出这个结论是因为我错过了这样的逻辑:

on every year that is evenly divisible by 4
and also evenly divisible by 100
and also evenly divisible by 400

我的问题是,为什么这会起作用?

我不确定为什么我不使用 && 操作数,但话又说回来,它不会那样工作

最佳答案

让我们看一下谓词yearModFour ===yearModHundred ===yearModFourHundred,并列出一些将导致所有可能性的数字。

对于第 1 年,谓词的计算结果为:

(False === False) === False
True === False
False

对于第 4 年,谓词的计算结果为:

(True === False) === False
False === False
True

对于第 100 年,谓词计算为:

(True === True) === False
True === False
False

对于第 400 年,谓词的计算结果为:

(True === True) === True
True === True
True

现在这就是所有的可能性,这里不会有任何其他可能性。这是因为任何能被 400 整除的数字都可以被 100、4 和 1 整除;任何能被 100 整除的数也能被 4 和 1 整除;等等。

所以你的结论并不完全正确,因为它暗示了所有模运算之间的逻辑“与”。

关于javascript - 闰年功能;这个解决方案如何运作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53168452/

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