输入一个年份和这一年是星期几, 输出一年的日历。C++程序设计, 5.31

        最近学习C++语言, 用的是《C++程序设计》这本书, 在做书上习题, 这是第五章第31题, 题目是:输入年份和这一年的第一天是星期几, 然后输出一整年的日历。由于是新手, 用了我大概一个多小时的时间。

         这个代码是要求用户输入年份和这一年的第一天是星期几的, 当然也可以只输入年份, 星期几可以根据基姆拉尔森公式 计算, 不过我没有写在代码里。

        下面代码在我的机器上运行是没有问题的, 我用的是Manjaro Linux, IDE是Clion。主要是记录个人的学习, 仅供个人日后参考, 如有错误, 还希望不吝赐教。

#include <iostream>
#include <iomanip>
#define WEEK 7

using namespace std;

int print_days(int whitespace, int days){
    int count =0, day = 0;
	while(whitespace != 0){
		cout << setw(5) << " ";
		whitespace--;
		count++;
	}
	while(day < days){
		if(count < WEEK - 1){
			cout << setw(5) << day+1;
			day++;
			count++;
		}
		else{
			cout << setw(5) << day+1 << endl;
			day++;
			count = 0;
		}
	}
	return count;
}
int main(){
	
	bool isLeap;
	bool bigMonth = true;
	bool feb = false;
	int days = 31;
	string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	string weekdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	
	cout << "输入一个年份" << endl;
	int year;
	cin >> year;
	
	cout << "请输入一个星期" << endl;
	int week;
	cin >> week;
	
	isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
	
	int month = 0;
	int whitespace = week;
	
	for (int m=0; m<12; m++){
		int count = 0;
		cout << setw(20) << months[month] << "  " <<year << endl;
		month++;
		cout << "  __________________________________ " << endl << endl;
		for (int j=0; j < WEEK; j++){
			cout << setw(5) << weekdays[j];
		}
		cout << endl;		
		if(bigMonth){
            whitespace = print_days(whitespace, days);
//			whitespace = count;
			bigMonth = false;
			if(month==7) bigMonth = true;
			if(month==1) feb = true;
			days = 30;
			if(month==7) days = 31;
			if(month==1) days = isLeap?29:28;
			cout << endl << endl;	
		}
		else if(!bigMonth && !feb){
			whitespace = print_days(whitespace, days);
//			whitespace = count;
			bigMonth = true;		
			days = 31;		
			cout << endl << endl;		
		}
		else{
            whitespace = print_days(whitespace, days);
//			whitespace = count;
			feb = false;
			bigMonth = true;		
			days = 31;		
			cout << endl << endl;
		}	
	}
}

 

运行结果(部分)

 

 

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值