【问题标题】:Why use identical statements?为什么使用相同的语句?
【发布时间】:2021-04-15 22:15:22
【问题描述】:

我正在学习关于 Udemy 的课程,但我对问题的解决方案感到困惑。问题是创建一个函数来确定一年是否为闰年。

解决办法是:

function isLeap(year) {
    
/**************Don't change the code above****************/    
    
    //Write your code here.    
if (year % 4 === 0){

if (year % 100 === 0){

if (year % 400 === 0){

  return ("Leap year.")
}
} else {

  return ("Leap year.")

}
} else {

  return ("Not leap year.")

}
isLeap(1948);

    

/**************Don't change the code below****************/    

}

如果满足这些条件,当上面已经使用else return ("Leap year") 时,我对它的使用感到困惑。我是否遗漏了与代码流动方式有关的内容?

【问题讨论】:

  • 如果你修复你的大括号和缩进,你会看到你缺少什么。

标签: javascript function if-statement


【解决方案1】:
function isLeap(year) {
    /**************Don't change the code above****************/

    //Write your code here.
    if (year % 4 === 0) {
        if (year % 100 === 0) {
            if (year % 400 === 0) {
                return "Leap year.";
            }
        } else {
            return "Leap year.";
        }
    } else {
        return "Not leap year.";
    }
    isLeap(1948);

    /**************Don't change the code below****************/
}

首先,您需要正确格式化您的代码。您可以为此使用Prettier。 如果你这样做,你会注意到这个 sn-p 一切都很好,而且这个算法实际上与 wikipedia 上提出的算法相匹配。

值得一提的是,该算法效率低下,如果您想了解更多关于此的信息,here 是一个很好的起点:)

【讨论】:

  • 谢谢 Gregooroo,感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 2023-03-22
相关资源
最近更新 更多