面向对象第一次实验参考代码

本文介绍了一个简单的C++程序,用于创建日期类,实现日期的有效性检查、判断是否为闰年及计算一年中的第几天等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream.h>  
#include <stdlib.h>  

//Global variable  
int days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};//days of month  
char *Week[7] = {"Sunday","Monday","Tuesday","Wednesday","Thurday","Friday","Saturday"};  //Week  

class Date{//class defination  
public:  
    void SetDate(int,int,int);// initialization  
    int IsLeapyear(int );  //Leap year or not  
    int Week_day(int);  //Week_day  
    void Show();  //days number  
private:  
    int year,month,day;  
};  

void Date::SetDate(int y,int m,int d)  
{  
    year = y;  
    month = m;  
    day = d;  
    if(year <= 0 || month <= 0 || day <= 0 || month > 12
		 || day > days[month])  //Date validity check  
    {  
        cout<<"The Date is invalid!"<<endl;  
        exit(0);  
    }  
}  

int Date::IsLeapyear(int y)  
{  
    return y % 4 == 0 && y % 100 != 0 || y % 400 == 0;  
}  

int Date::Week_day(int flag)    
//flag 0:week 1:day_num;  
{  
    long sum = 0;  
    int i;  
    if(flag == 0)  
        i = 1;  
    else  
        i = year;  
    for(;i < year;i++)  
    {  
        if(IsLeapyear(i))  
            sum += 366;  
        else  
            sum += 365;  
    }  
    for(int j = 1;j < month;j++)  
        sum += days[j];  
    if(month > 2 && IsLeapyear(year))  
        sum++;  
    sum += day;  
    if(flag == 0)  
        return sum % 7;  
    return sum;  
};  

void Date::Show()  
{  
    cout<<"The Date is:"<<year<<"-"<<month<<"-"<<day<<endl;  
    cout<<"It's "<<*(Week+Week_day(0))<<endl;  
    cout<<"It's "<<Week_day(1)<<" days of this year!"<<endl;  
}  

void main()  
{  
    Date D;  
    int y,m,d;  
    cout<<"Please input the Date:"<<endl;  
    cin>>y>>m>>d;  
    D.SetDate(y,m,d);  
    D.Show();  
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值