题目:
给定一个日期,输出这个日期是该年的第几天。
input
输入数据有多组,每组占一行,数据格式为YYYY/MM/DD组成,具体参见sample input ,另外,可以向你确保所有的输入数据是合法的。
output
对于每组输入数据,输出一行,表示该日期是该年的第几天。
#include <iostream>
using namespace std;
int main()
{
char data[20];
int day,month,year,tmp,i;
while (cin >> data) {
i = 0;
day = 0; month = 0; year = 0; tmp = 0;
while (data[tmp] != '/') {
year *= 10;
year += data[tmp]-48;
tmp++;
}
tmp++;
while (data[tmp] != '/') {
month *= 10;
month += data[tmp]-48;
tmp++;
}
tmp++;
while (data[tmp] != '/'&&i<1) {
day *= 10;
day += data[tmp]-48;
if (data[tmp + 1] != NULL) {
day *= 10;
day += data[tmp+1] - 48;
}
tmp++;
i++;
}
//cout << "year" << year << "month" << month << "day" << day;
int num = 0;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
int dayData[12] = { 31,29,31,30,31,30,31,31,30,31,30,31 };
for (int i = 0; i < month - 1 && month>1; i++) {
num += dayData[i];
}
num += day;
}
else {
int dayData[12] = { 31,28,31,30,31,30,31,31,30,31,30,31};
for (int i = 0; i < month-1&&month>1; i++) {
num += dayData[i];
}
num += day;
}
cout << num<<endl;
}
}
关键语句:
if (data[tmp + 1] != NULL) {
day *= 10;
day += data[tmp+1] - 48;
}
改进版
#include<cstdio>
int main() {
unsigned int year, month, day;
while (scanf_s("%d/%d/%d", &year, &month, &day) != EOF) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
int data[11] = { 31,29,31,30,31,30,31,31,30,31,30 };
for (int i = 0; i < month - 1; i++) {
day += data[i];
}
}
else {
int data[11] = { 31,28,31,30,31,30,31,31,30,31,30 };
for (int i = 0; i < month - 1; i++) {
day += data[i];
}
}
printf("%d\n", day);
}
}