比较两人生日相差多少天
算法:从键盘输入出生日期,取较小者的年份为基准,先计算其中一个生日距基准年份的第一天相差天数,再计算第二个,再将两个结果做差即可
如输入2015 2 14
2013 4 28
则基准为2013 1 1
#include "stdafx.h"
#include<stdio.h>
int time(int a, int b, int c, int year); //申明函数time
struct student{
int year;
int month;
int day;
}c[2]; //定义两位学生结构体和变量
int main()
{
int i, sum1 = 0, sum2 = 0, sum;
for (i = 0; i<2; i++)
{
printf("请输入第%d位同学生日:", i + 1);
scanf_s("%d %d %d", &c[i].year, &c[i].month, &c[i].day);
} //输入两位同学生日信息
if (c[0].year >= c[1].year)
{
sum1 = time(c[0].year, c[0].month, c[0].day, c[1].year);
sum2 = time(c[1].year, c[1].month, c[1].day, c[1].year);
}
else
{
sum1 = time(c[0].year, c[0].month, c[0].day, c[0].year);
sum2 = time(c[1].year, c[1].month, c[1].day, c[0].year);
} //用小一点的同学出生年份做基准
sum = (sum1 >= sum2) ? (sum1 - sum2) : (sum2 - sum1); //输出正的天数
printf("两人相差%d天\n", sum);
}
int time(int a, int b, int c, int year) //定义函数time
{
int num = 0, i, sum = c;
for (i = 1; i<b; i++)
{
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:num = 31; break;
case 4:
case 6:
case 9:
case 11:num = 30; break;
case 2:if (a % 4 == 0 && a % 100 != 0 || a % 400 == 0)
num = 29;
else
num = 28;
break;
default:num = 0;
}
sum += num; //统计该同学生日和他出生那年第一天差
}
if (a == year)
return sum;
else if (a>year)
{
for (i = year; i<a; i++) //循环是用来大一点同学大出年份的总天数
{
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
sum += 366;
else
sum += 365;
} //求出总天数
return sum;
}
}