1270 - C语言11.6
定义一个包括年、月、日的结构体变量,读入年、月、日,计算该日在当年中是第几天。注意闰年问题。
请写一个函数days实现计算,将读入的结构体变量传递给days函数,计算后将答案返回给main函数进行输出。
Input
三个整数,分别表示年、月、日。保证输入是实际存在的日期,且年份在1000至3000之间(包含1000和3000)。
Output
输出该日期是一年中的第几天。
请注意行尾输出换行。
Examples
Input
2012 12 21
Output
356
Solution C
#include<stdio.h> int ok(int n) { if(n%100==0) {if(n%400==0) return 1; else return 0; } else if( n%4==0) return 1; else return 0; } int main() { int i,x,y,z,sum=0; int a[]={31,29,31,30,31,30,31,31,30,31,30,31}; int b[]={31,28,31,30,31,30,31,31,30,31,30,31}; scanf("%d%d%d",&x,&y,&z); if(ok(x)) { for(i=1;i<y;i++) sum+=a[i-1]; sum+=z; } else { for(i=1;i<y;i++) sum+=b[i-1]; sum+=z; } printf("%d\n",sum); return 0; }
Solution C++
#include <stdio.h> struct date { int year, month, day; }; int main() { int days(struct date today); struct date today; scanf("%d %d %d", &today.year, &today.month, &today.day); printf("%d\n", days(today)); return 0; } /* 计算输入的日期是当年的第几天 */ int days(struct date today) { int is_leap_year(int year); int day_of_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int i, totdays = 0; for (i = 1;i < today.month;i++) { totdays += day_of_month[i - 1]; if (i == 2 && is_leap_year(today.year) == 1) totdays++; } totdays += today.day; return totdays; } /* 判断是否是闰年 */ int is_leap_year(int year) { if (year % 4 == 0) { if (year % 100 == 0 && year % 400 != 0) return 0; return 1; } return 0; }