1. 程式人生 > >第五週專案3-時間類(2)修改

第五週專案3-時間類(2)修改

修改原因:在上一篇博文中第五週專案3-時間類(2)中提交的程式碼存在一些問題:

 (1) 老師給出的程式碼中,輸入60或24也算作合法時間,但是在現實生活中並不存在這樣的時間,所以要把程式碼改一下;

(2)當輸入的要增加的秒,分,小時數加上原本的時,分,秒數大於60或者24的時候,只能進1位,如果數字過大,就會導致秒,分超限。在課上聽了老師的講解後意識到這一問題,並進行了改正:

錯誤結果:

改正後程式碼:

#include<iostream>
using namespace std;
class time
{
public:
    void set_time();
    void show_time();
    void add_seconds(int x);
    void add_minutes(int y);
    void add_hours(int z);
private:
    bool is_time(int ,int ,int);
    int hour;
    int minute;
    int sec;
};
void time::add_seconds(int x)
{
    sec+=x;
    if(sec>=60)
    {
        minute+=sec/60;
        sec=sec%60;

    }
}
void time::add_minutes(int y)
{
    minute+=y;
    if(minute>=60)
    {
         hour+=minute/60;
        minute=minute%60;

    }
}
void time::add_hours(int z)
{
    hour+=z;
    if(hour>=24)
    {
        hour=hour%24;
    }
}
void time::set_time()
{
    char c1,c2;
    cout<<"請輸入時間(格式hh:mm:ss)";
    while(1)
    {
        cin>>hour>>c1>>minute>>c2>>sec;
        if(c1!=':'||c2!=':')
            cout<<"格式不正確重輸"<<endl;
        else if(!is_time(hour,minute,sec))
            cout<<"時間非法,請重新輸入"<<endl;
        else
            break;
    }
}void time::show_time()
{
    cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
bool time::is_time(int h,int m,int s)
{
    if(h<0||h>=24||m>=60||m<0||s<0||s>=60)
        return false;
    return true;
}
int main()
{
    int x,y,z;
    time t1;
    t1.set_time();
    cin>>z>>y>>x;
    t1.add_seconds(x);
    t1.add_minutes(y);
    t1.add_hours(z);
    t1.show_time();
    return 0;
}


正確的執行結果: