繁安
繁安

喜歡開發腦洞,如果能讓你對人生有新的啟發,會是我最大的榮幸。 #心靈治愈 #星盤 #普通分享 #隨筆 #自學前端ing

用Chatgpt來學習|閏年計算JavaScript

(编辑过)
利用Chatgpt學習用JavaScript來計算閏年的一些方法 //超基本JS code

若要判斷年份是否為閏年,請依照下列步驟執行:

  1. 如果年份被 4 整除,則移至步驟 2。
  2. 如果年份被 100 整除,則移至步驟 3。
  3. 年份被 400 整除。

節錄自https://learn.microsoft.com/zh-tw/office/troubleshoot/excel/determine-a-leap-year

方法1:
function isLeapYear(year) {
    if (year % 4 !== 0) {
      // If the year is not divisible by 4, it's not a leap year
      return false;
    } else if (year % 100 !== 0) {
      // If the year is divisible by 4 but not by 100, it's a leap year
      return true;
    } else if (year % 400 !== 0) {
      // If the year is divisible by 100 but not by 400, it's not a leap year
      return false;
    } else {
      // If the year is divisible by both 100 and 400, it's a leap year
      return true;
    }
  }
//   You can call this function with a year as an argument, like this:
  
 console.log(isLeapYear(2020)); // Output: true
 console.log(isLeapYear(2021)); // Output: false
方法2:
function isLeap(year) {
  if (year % 4 === 0) {
    if (year % 100 === 0) {
      if (year % 400 === 0) {
        return "It is a leap year";
      } else {
        return "It is not a leap year";
      }
    } else {
      return "It is a leap year";
    }
  } else {
    return "It is not a leap year";
  }
}
方法3(最短):
function isLeap(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论