qt c++ 实现一个函数,输入的参数为Qstring,实现每一天调用qDebug()<<"day";考虑闰年平年和大小月,范围为某年某月某日到某年某月某日,并计算总的天数
时间: 2024-03-26 07:34:09 浏览: 57
好的,根据你的要求,这里提供一个输入参数为QString类型的函数实现,该函数实现了每一天调用qDebug()<<"day",并考虑了闰年平年和大小月,范围为某年某月某日到某年某月某日,并计算总天数。代码如下:
```cpp
#include <QtCore>
int daysInMonth(int year, int month) {
if (month == 2) {
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
return 29;
} else {
return 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
int daysBetween(QString startDateStr, QString endDateStr) {
QDate startDate = QDate::fromString(startDateStr, "yyyy-MM-dd");
QDate endDate = QDate::fromString(endDateStr, "yyyy-MM-dd");
int days = 0;
for (int year = startDate.year(); year <= endDate.year(); ++year) {
int startMonth = (year == startDate.year() ? startDate.month() : 1);
int endMonth = (year == endDate.year() ? endDate.month() : 12);
for (int month = startMonth; month <= endMonth; ++month) {
int startDay = (year == startDate.year() && month == startDate.month() ? startDate.day() : 1);
int endDay = (year == endDate.year() && month == endDate.month() ? endDate.day() : daysInMonth(year, month));
for (int day = startDay; day <= endDay; ++day) {
qDebug() << "day";
++days;
}
}
}
return days;
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QString startDateStr = "2020-01-01";
QString endDateStr = "2020-01-31";
int totalDays = daysBetween(startDateStr, endDateStr);
qDebug() << "Total days:" << totalDays;
return app.exec();
}
```
这个程序中,我们定义了一个输入参数为QString类型的函数daysBetween,该函数实现了从起始日期到结束日期的天数计算,并在每个日期上调用qDebug()<<"day"。在main函数中,我们可以设置起始日期和结束日期的字符串,并调用daysBetween函数来计算总天数。
阅读全文