C&C++:计算某年某月的1号是星期几

C&C++函数实训-这天星期几?

任务描述

本关任务:编写函数 whatDay,计算某年某月的1号是星期几并返回。

相关知识

要知道某一天是星期几,可以用已知的某一天进行推导。

例如已知公元1年1月1日是星期一,公元2年1月1日则是在星期一基础上加上一整年的天数(要考虑闰年,闰年一年366天,非闰年365天),如果不是1月,例如7月,则要加上1到6月的所有天数,这里也要考虑闰年,因为闰年的二月是29天,非闰年是28天。

这样就可以算出从公元1年1月1日到该年月过了多少天,而过了7天星期不变,所以可以用这种方法推导出公元元年之后的任何一天是星期几。

下面的程序可以计算星期一过了 n 天后是星期几:

 
  1. w = 1; // 从星期一开始
  2. w = w + n; // n天后
  3. w = w % 7; // 得到0-6,其中0为星期天
  4. // 调整星期天
  5. if(w == 0) w = 7;

编程要求

计算输入数据年月份的1号是星期几并返回(周一到周日分别返回整数1到7)。

其中该函数的参数为输入的两个整数数据:年和月。

提示:由于判断是否闰年有多个地方需要用到,故已把该功能单独实现为一个函数。

 代码如下(已删去注释):

#include<iostream>
using namespace std;

int leapYear(int y){
    if (y%4==0 && y%100 !=0 || y%400==0 ) return 1;
    return 0;
}

int whatDay(int year,int month){
    int dyear=0,nd=0,w,lyear=0;
    if (year==1) nd = 0 ; else {
        for (int i=1;i<year;i++) {
            if (leapYear(i)) lyear+=1;
            else dyear+=1;
        }
        nd=dyear*365+lyear*366;
    }
    if (month==1) nd+=1; else {
        int monthl[]={1,31,0,31,30,31,30,31,31,30,31,30,31};
        for (int j=0;j<=month-1;j++) {
            nd+=monthl[j];
        }
    if (leapYear(year) && month >=3 ) nd+=29;
    if (leapYear(year)==0 && month >=3 ) nd+=28;
    }
    w=0;
    w+=nd;
    w=w%7;
    if (w==0) w=7;
    return w;
}

int main()
{
    int y , m , xq ;
    cin >> y >> m ;
    xq=whatDay(y,m);
    cout << y << "年" << m << "月1日是星期";
    if   (xq==7) cout << "日" << endl ;
    else         cout <<  xq  << endl ;
    return 0;
}

下面是一个简单的C++程序,实现了万年历的功能: ```c++ #include <iostream> #include <cstring> using namespace std; // 存储每个月的天数 const int daysInMonth[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 判断是否是闰年 bool isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } // 获取某年某月的天数 int getDaysInMonth(int year, int month) { if (month == 2 && isLeapYear(year)) { return 29; } return daysInMonth[month]; } // 获取某年某月1星期 int getFirstDayOfWeek(int year, int month) { int y = year, m = month; if (m == 1 || m == 2) { m += 12; y--; } int c = y / 100, d = y % 100; int w = (c / 4) - 2 * c + d + (d / 4) + ((13 * (m + 1)) / 5) + 1; return (w % 7 + 7) % 7; } int main() { int year, month; cout << "请输入年份:"; cin >> year; cout << "请输入月份:"; cin >> month; int days = getDaysInMonth(year, month); // 获取该月天数 int firstDayOfWeek = getFirstDayOfWeek(year, month); // 获取该月1星期 // 打印历头部 cout << "\t一\t二\t三\t四\t五\t六" << endl; // 定位到第一天所在的星期 for (int i = 0; i < firstDayOfWeek; i++) { cout << "\t"; } // 输出期 for (int i = 1; i <= days; i++) { cout << i << "\t"; if ((i + firstDayOfWeek) % 7 == 0) { // 换行 cout << endl; } } return 0; } ``` 该程序主要思路是先计算某年某月的天数和该月1星期,然后根据这些信息输出历。在输出历时,我们需要先打印历头部,然后定位到第一天所在的星期,最后按天输出期。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值