2つの日付間の合計日数を求める問題を解決しようとしています。私は、うるう年やユーザーが年を入力する方法など、この2つの日付の間にいくつかの問題を処理する必要があります。 (たとえば、1と17を入力した場合、コードでは16年(2017 - 2001 = 16)の差が残っていますが、main()関数の中で何も変更する必要はありません。2日間の合計日数C++
#include <iostream>
#include <cmath>
using namespace std;
class date
{
private:
int m;
int d;
int y;
public:
date(int, int, int);
int countLeapYears(date&);
int getDifference(date&);
int operator-(date&);
};
int main()
{
int day, month, year;
char c;
cout << "Enter a start date: " << endl;
cin >> month >> c >> day >> c >> year;
date start = date(month, day, year);
cout << "Enter an end date: " << endl;
cin >> month >> c >> day >> c >> year;
date end = date(month, day, year);
int duration = end-start;
cout << "The number of days between those two dates are: " <<
duration << endl;
return 0;
}
date::date(int a, int b, int c)
{
m = a;
d = b;
y = c;
}
const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31};
int date::countLeapYears(date& d)
{
int years = d.y;
if (d.m <= 2)
years--;
return years/4 - years/100 + years/400;
}
int date::getDifference(date& other)
{
int n1 = other.y*365 + other.d;
for (int i=0; i<other.m - 1; i++)
{
n1 += monthDays[i];
n1 += countLeapYears(other);
}
return n1;
}
int date::operator-(date& d) {
int difference = getDifference(d);
return difference;
}
私は上記のコードに問題があり、私はそれを実行したときに、 "日付"と "日付"の間に無効なバイナリ演算があると言っていました。私は自分の関数getDifferenceがすでにその問題を処理していると思っていました。 、私はその問題の世話をしなかったようだ。
'2007 - 2001'は' 7と同じものです - 1 '、私は本当にそれについてdicey何が表示されません。 –
私はあなたが言っていることを理解していません。 –
あなたの質問は理解しにくいです。ユーザーが '2007年 'と入力したように入力' 7'を受け入れるべきであることを意味しますか?もしそうなら、入力された年が '2000'よりも小さいかどうかをチェックし、その場合は' 2000'を加えてください。 – DUman