一开始觉得很简单,后来想了想感觉不简单,要考虑闰年闰月。
我吐了,就是不行:
#include<iostream>
#include<math.h>
#include<string>
#include <iomanip>
#include<stdio.h>
using namespace std;
bool isleap(int year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
return 1;
else
return 0;
}
int month[13] = {0, 31,28,31,31,30,31,31,30,31,30,31 };
int main()
{
string n,m;
while (cin >> n>>m) {
int sum = 0;
string a;
string b;
string c;
string d;
string e;
string f;
for (int i = 0; i <4; i++) {
a.push_back(n[i]);
d.push_back(m[i]);
}
for (int i = 0; i < 2; i++) {
b.push_back( n[i+4]);
e.push_back (m[i + 4]);
}
for (int i = 0; i < 2; i++) {
c.push_back(n[i+6]);
f.push_back (m[i + 6]);
}
if (stoi(a) != stoi(d)) {//不同年
int s = 0;
if (isleap(stoi(a)) == 1) {
month[2] = 29;
for (int i = 1; i < stoi(b); i++) {
s += month[i];
}
s += stoi(c);
sum = sum + (366 - s);
}
if (isleap(stoi(a)) == 0) {
for (int i = 1; i < stoi(b); i++) {
s += month[i];
}
s += stoi(c);
sum = sum + (365 - s);
}
for (int i = stoi(a)+1; i < stoi(d); i++) {
if (isleap(i) == 1) { sum += 366; }
else sum += 365;
}
if (isleap(stoi(d)) == 1) {
month[2] = 29;
for (int i = 1; i < stoi(e); i++) {
sum += month[i];
}
}
if (isleap(stoi(d)) == 0) {
for (int i = 1; i < stoi(e); i++) {
sum += month[i];
}
}
sum += stoi(f);
}
else {
if (stoi(e) != stoi(b)) {
if (isleap(stoi(d)) == 1) {
month[2] = 29;
sum = sum + (month[stoi(b)] - stoi(c));
for (int i = stoi(b)+1; i < stoi(e); i++) {
sum += month[i];
}
}
if (isleap(stoi(d)) == 0) {
sum = sum + (month[stoi(b)] - stoi(c)+1);
for (int i = stoi(b)+1; i < stoi(e); i++) {
sum += month[i];
}
}
sum += stoi(f);
}
else {
if(stoi(f)-stoi(c)!=1)sum += stoi(f) - stoi(c)+1;
if (stoi(f) - stoi(c) == 1)sum += 2;
}
}
cout << sum << endl;
}
return 0;
}
不搞了,下一道。过几天回来看。
几个没考虑的问题:第a年的天数不是简单的365/366
用一个整型数组储存每月天数。
看了算法笔记之后
上次写的很多问题,最离谱的一个:月份数组写错了,然后忘记了如果第一个数大于第二个数要交换的事情。并且我写的太繁琐了。算法笔记给的思路:从当前天一天一天往后加,若月份满了则进一月,日期为1号;年份满了进一年,月份为一月,还有开辟二维数组,第二维是闰年的月份天数,这样判断很简单。
代码:
#include<iostream>
#include<math.h>
#include<string>
#include <iomanip>
#include<stdio.h>
using namespace std;
bool isleap(int year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
return 1;
else
return 0;
}
int month[13][2] = { { 0,0} ,{31,31}, {28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31} };
int main()
{
int t1, y1, m1, d1;
int t2, y2, m2, d2;
while (cin >> t1 >> t2) {
if (t1 > t2) {
int tmp = t2;
t2 = t1;
t1 = tmp;
}
y1 = t1 / 10000; m1 = t1 % 10000 / 100; d1 = t1 % 100;
y2 = t2 / 10000; m2 = t2% 10000 / 100; d2= t2 % 100;
int ans = 1;
while (y1 < y2 || m1 < m2 || d1 < d2) {
d1++;
if (d1 == month[m1][isleap(y1)] + 1) {
m1++;
d1 = 1;
}
if (m1 == 13) {
y1++;
m1 = 1;
}
ans++;
}
cout << ans << endl;
}
return 0;
}
不容易哈……