声明一个结构体类型Date,包括年月日,即一个日期类型的结构体。
设计一个程序,完成以下对日期的操作,包括以下函数:
Date AddDay(Date d, int days):对日期增加days天数,然后返回得到的日期
Date AddMonth(Date d, int months):对日期增加months月数,然后返回得到的日期
Date AddYear(Date d, int years):对日期增加years年数,然后返回得到的日期
int Subtract(Date d1, Date d2):用d1-d2,计算它们相距的天数,作为函数值返回
GetWeekDay:输入参数为Date类型,返回该日期是星期几。星期几最好用枚举表示,也就是返回一个枚举类型的值。
程序输出相应计算结果。
第四,五个函数不会写,而且函数返回值不止一个时不知道怎么返回。
返回多个值的时候可以写成一个数组或其他类型的集合返回,如果是迭代函数的话,可以用ref
返回Date类型的结构体就可以了
c++可以使用引用进行返回值,以值结果的形式,比如传递int a,可以利用指针方式int *value,或者引用int &value。
函数需要有多个输出时,如果这多个具有关联性,可以选择用一个结构体将它们组织起来,就好像你的Date结构体那样。你也可以选择在函数的参数里使用指针作为输出参数,例如 sample(int input, int *output) 这样。
仅供参考
#include<iostream>
using namespace std;
struct Date
{
int year;
int month;
int day;
};
int GetAbsDays(Date x)
{
int i;
int month_day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int year = x.year-1; // 因为欲求距离1年1月1日的距离
int days = year * 365 + year/4 - year/100 + year/400; //求得之前闰年的数量并在天数上进行想加
if(x.year%4==0 && x.year%100!=0 || x.year%400==0) month_day[1]++; //当前年为闰年,二月加 1
for(i=0; i<x.month-1; i++)
days += month_day[i];
days += x.day-1; //今天应该是不算如天数计数
return days;
}
int Subtract(Date a, Date b)
{
return GetAbsDays(b) - GetAbsDays(a);
}
int GetWeekDay(Date date)
{
int iWeek = 0;
int iYear = date.year;
int iMonth = date.month;
int iDay = date.day;
unsigned int y = 0, c = 0, m = 0, d = 0;
if ( iMonth == 1 || iMonth == 2 )
{
c = ( iYear - 1 ) / 100;
y = ( iYear - 1 ) % 100;
m = iMonth + 12;
d = iDay;
}
else
{
c = iYear / 100;
y = iYear % 100;
m = iMonth;
d = iDay;
}
iWeek = y + y / 4 + c / 4 - 2 * c + 26 * ( m + 1 ) / 10 + d - 1; //蔡勒公式
iWeek = iWeek >= 0 ? ( iWeek % 7 ) : ( iWeek % 7 + 7 ); //iWeek为负时取模
return iWeek;
}
enum WEEKDAY{sun,mon,tue,wed,thu,fri,sat}week_day;
int main(int argc, char* argv[])
{
Date a = {2000,5,18};
Date b = {2016,3,13};
int n = Subtract(a,b);
printf("%d\n", n);
int m = GetWeekDay(b);
cout << m << endl;
system("pause");
}
返回多个值可以用C++里面的pair,如part