c++编程语言用一维数组存放12个月的天数,编写程序,从键盘输入年、月、日,输出该日期是本年的第几天。
时间: 2024-10-27 16:07:21 浏览: 14
在C++中,我们可以创建一个一维数组来存储每个月的天数,并利用这个信息来计算给定日期是当年的第几天。首先,我们需要预定义一个数组存储每个月的天数,然后让用户输入年份、月份和日期,通过遍历前几个月的总天数来计算当前日期的位置。下面是一个简单的示例程序:
```cpp
#include <iostream>
using namespace std;
const int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 闰年忽略
int main() {
int year, month, day;
cout << "请输入年份:";
cin >> year;
if (is_leap_year(year)) { // 判断是否为闰年
days_in_month[1] = 29; // 如果是闰年,二月有29天
}
cout << "请输入月份(1-12):";
cin >> month;
month--; // 因为数组索引从0开始,所以实际的月份需要减1
cout << "请输入日期:";
cin >> day;
int total_days = 0;
for (int i = 0; i < month; ++i)
total_days += days_in_month[i];
total_days += day; // 加上本月的日数
cout << "该日期是本年的第" << total_days+1 << "天。"; // 提供一天的偏移,因为从1开始计数
return 0;
}
bool is_leap_year(int year) {
if (year % 4 != 0) return false;
if (year % 100 != 0) return true;
if (year % 400 != 0) return false;
return true;
}
```
在这个程序中,我们假设用户输入的是标准的阳历年份(即平年365天,闰年366天),如果是闰年,我们会更新二月的天数为29。
阅读全文