用Chatgpt来学习|闰年计算JavaScript

2023-04-28分类:人工智能 阅读(


利用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);
}

Tags: ChatGPT