c++初学者求解一道结构体，函数题

int Subtract(Date d1, Date d2)：用d1-d2，计算它们相距的天数，作为函数值返回

GetWeekDay：输入参数为Date类型，返回该日期是星期几。星期几最好用枚举表示，也就是返回一个枚举类型的值。

6个回答

c++可以使用引用进行返回值，以值结果的形式，比如传递int a，可以利用指针方式int *value，或者引用int &value。

`````` #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");
}
``````