C++ 代码:计算某年某月某日是该年的第几天
以下是使用 Dev C++ 编写的代码,可以根据输入的年月日,判断是这一年的第几天:
#include <stdio.h>
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1; // 是闰年
}
return 0; // 不是闰年
}
int getDayOfYear(int year, int month, int day) {
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int dayCount = 0;
if(isLeapYear(year)) {
daysInMonth[1] = 29; // 闰年二月为29天
}
for(int i = 0; i < month - 1; i++) {
dayCount += daysInMonth[i];
}
dayCount += day;
return dayCount;
}
int main() {
int year, month, day;
printf('请输入年份:');
scanf('%d', &year);
printf('请输入月份:');
scanf('%d', &month);
printf('请输入日期:');
scanf('%d', &day);
int dayOfYear = getDayOfYear(year, month, day);
printf('这是%d年的第%d天。\n', year, dayOfYear);
return 0;
}
注意:以上代码假设输入的年、月、日都是合法的,并未进行输入错误的判断,如需完善可根据实际需求进行修改。
原文地址: http://www.cveoy.top/t/topic/coWB 著作权归作者所有。请勿转载和采集!