单片机/MCU论坛
直播中

jf_76693375

3年用户 197经验值
擅长:可编程逻辑,控制/MCU
私信 关注
[资料]

有趣的黑色星期五代码

  1. #include
  2. #include
  3. // 判断是否为闰年
  4. int isLeapYear(int year) {
  5.     return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
  6. }
  7. // 计算指定年份黑色星期五数量并列出具体日期
  8. void GetYearBlackFriday(int year) {
  9.     int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  10.     char *months[12] = {"一月", "二月", "三月", "四月", "五月", "六月",
  11.                         "七月", "八月", "九月", "十月", "十一月", "十二月"};
  12.    
  13.     if (isLeapYear(year)) {
  14.         days[1] = 29;
  15.     }
  16.    
  17.     int count = 0;
  18.     int totalDays = 0;
  19.    
  20.     // 计算从1900年到指定年份前一年的总天数
  21.     for (int y = 1900; y < year; y++) {
  22.         if (isLeapYear(y)) {
  23.             totalDays += 366;
  24.         } else {
  25.             totalDays += 365;
  26.         }
  27.     }
  28.    
  29.     printf("%d年的黑色星期五日期如下:\n", year);
  30.    
  31.     for (int month = 0; month < 12; month++) {
  32.         // 计算当前月份13号是星期几
  33.         int weekday = (totalDays + 13) % 7;
  34.         
  35.         if (weekday == 5) {
  36.             printf("%s 13日\n", months[month]);
  37.             count++;
  38.         }
  39.         
  40.         // 累加当前月份的天数
  41.         totalDays += days[month];
  42.     }
  43.    
  44.     printf("\n%d年共有%d个黑色星期五\n", year, count);
  45. }
  46. int main() {
  47.     int year;
  48.     while (1) {
  49.         printf("请输入年份(输入0退出):");
  50.         scanf("%d", &year);
  51.         
  52.         if (year == 0) {
  53.             break;
  54.         }
  55.         
  56.         if (year < 1900) {
  57.             printf("年份必须大于等于1900\n");
  58.             continue;
  59.         }
  60.         
  61.         GetYearBlackFriday(year);
  62.     }
  63.    
  64.     return 0;
  65. }

更多回帖

发帖
×
20
完善资料,
赚取积分