输入年月日,用程序计算这一天是这一年的第几天,用C++,怎么编?

如题所述

#include <iostream> using namespace std; #define INVALID_VALUE 0xFFFFFFFF int CalcDays(const int nYear, const int nMonth, const int nDay){ if(nYear < 0 || (nMonth < 1 || nMonth > 12) || (nDay < 1 || nDay > 31)) return INVALID_VALUE; const static int nLDays[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; const static int nCDays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int res = 0; if(nYear%4==0 && nYear%100!=0 || nYear%400==0){ if(nDay > nLDays[nMonth]) return INVALID_VALUE; for(int i=0; i!=nMonth-1; ++i){ res += nLDays[i]; } res += nDay; } else { if(nDay > nCDays[nMonth]) return INVALID_VALUE; for(int i=0; i!=nMonth-1; ++i){ res += nCDays[i]; } res += nDay; } return res; } int main() { cout << "输入日期:"; int nYear, nMonth, nDay; cin >> nYear >> nMonth >> nDay; int res; if((res = CalcDays(nYear, nMonth, nDay)) != INVALID_VALUE){ cout << "该日期为该年的第" << res << "天."<<endl; } else { cout << "非法输入!" <<endl; } return 0; }
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-09-27
#include <time.h> #include <stdio.h> void main() { printf("输入年 月日\n"); tm t={0}; scanf("%d %d %d",&t.tm_year,&t.tm_mon,&t.tm_mday); t.tm_mon--; t.tm_year-=1900; t.tm_isdst=1; time_t tt=mktime(&t); t=*localtime(&tt); printf("第%d天\n",t.tm_yday+1); }
相似回答