我試圖解決一個問題,要求我給出兩個日期之間的總天數。我必須關注這兩個日期之間的一些問題,如閏年和用戶輸入年份的方式。 (例如,如果你輸入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;
}
我有一個問題與我上面的代碼,我需要你的幫助,請。當我運行它,它說:「日期」和「日期」之間的無效的二進制運算。現在,我想,當我初始化INT duration = end - start,我應該得到一個數字,我猜我在做什麼錯在這裏是我沒有把(結束 - 開始)日期類型轉換爲整數,我認爲我的函數getDifference已經處理了這個問題。 ,似乎我沒有照顧這個問題。
'2007 - 2001'是同樣的事情'7 - 1',我實在看不出有什麼冒險有關。 –
我不明白你在說什麼。 –
你的問題很難理解。你的意思是你應該接受輸入'7',就好像用戶輸入了'2007'一樣嗎?如果是這樣,只需檢查輸入的年份是否小於'2000',並在這種情況下添加'2000'。 – DUman