期中考试
编程题
1
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// 工具包头文件,用于存放函数声明 // 函数声明 bool isLeap(int);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// 功能描述: // 判断year是否是闰年, 如果是,返回true; 否则,返回false bool isLeap(int year) { if( (year % 4 == 0 && year % 100 !=0) || (year % 400 == 0) ) return true; else return false; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef DATE_H #define DATE_H class Date { public: Date(); // 默认构造函数,将日期初始化为1970年1月1日 Date(int y, int m, int d); // 带有形参的构造函数,用形参y,m,d初始化年、月、日 void display(); // 显示日期 int getYear() const; // 返回日期中的年份 int getMonth() const; // 返回日期中的月份 int getDay() const; // 返回日期中的日字 int dayOfYear(); // 返回这是一年中的第多少天 private: int year; int month; int day; }; #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "date.h" #include "utils.h" #include <iostream> using std::cout; using std::endl; Date::Date():year(1970),month(1),day(1){}; Date::Date(int y,int m,int d):year(y),month(m),day(d){}; void Date::display(){ cout<<year<<"-"<<month<<"-"<<day<<endl; } int Date::getYear()const{ return year; } int Date::getMonth()const{ return month; } int Date::getDay()const{ return day; } int Date::dayOfYear(){ int count=0; for(int i=1;i<month;i++){ if(i==1||i==3||i==5||i==7||i==8||i==10||i==12) count +=31; else if(i==2&&isLeap(year)==true) count +=29; else if(i==2&&isLeap(year)==false) count +=28; else count +=30; } count +=day; return count; } // 补足程序,实现Date类中定义的成员函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "utils.h" #include "date.h" #include <iostream> using namespace std; int main() { Date epochDate; epochDate.display(); cout << "是" <<epochDate.getYear()<<"年第"<< epochDate.dayOfYear() << "天.\n\n" ; Date today(2019,4,30); today.display(); cout << "是" <<today.getYear()<<"年第"<< today.dayOfYear() << "天.\n\n" ; Date tomorrow(2019,5,1); tomorrow.display(); cout << "是" <<tomorrow.getYear()<<"年第"<< tomorrow.dayOfYear() << "天.\n\n"; system("pause"); return 0; }