zl程序教程

您现在的位置是:首页 >  大数据

当前栏目

习题 7.1 定义一个结构体变量(包括年、月、日),编写程序,要求输入年、月、日,程序能计算并输出该日在本年中是第几天。注意闰年问题。

计算输入输出程序变量 一个 结构 定义
2023-09-14 09:06:56 时间

C++程序设计(第三版) 谭浩强 习题7.1 个人设计

习题 7.1 定义一个结构体变量(包括年、月、日),编写程序,要求输入年、月、日,程序能计算并输出该日在本年中是第几天。注意闰年问题。

代码块:

#include <iostream>
using namespace std;
struct Date
{
    int year;
    int month;
    int day;
};
void print(Date &dd);
int main()
{
    Date d;
    cout<<"Please enter date: ";
    cin>>d.year>>d.month>>d.day;
    print(d);
    system("pause");
    return 0;
}
void print(Date &dd)
{
    int i, m[12], sum=0;
    int y=dd.year;
    for (i=0; i<12; i++){
        if (y%4==0&&y%100!=0||y%400==0)
            m[1]=29;
        else m[1]=28;
        if (i==0||i==2||i==4||i==6||i==7||i==9||i==11)
            m[i]=31;
        else m[i]=30;
    }
    for (i=0; i<dd.month-1; sum+=m[i++]);
    cout<<"The date is No."<<sum+dd.day<<" days!"<<endl;
}