2014.05.30 武汉华科大活

题目:(原题不记得,大概回忆)用户输入一个时间,输出下一个时间

这个小题看似不难,实际处理起来对date的处理稍微繁琐,每月有30,31,28,29(闰年的判断)天四种可能

判定闰年:当不能被100整除且能被4整除时, 或能被400整除,为闰年

关键是如何让写出的代码规范且反应思路清晰,目前的代码见后文

当时居然没有意识到要用类,真是太菜了,没关系还不晚

 

虽然不难但比较繁琐,想要在笔试时用20~30分钟,在一张单面A4纸上,完整清晰的实现,

就需要思路很清晰不能大片修改,也没办法像上机一样调试,还是有难度的

自己写了时钟类,和++操作符重载,代码+测试结果如下:

//DataClock.h
#pragma once

//2014.05.30百田笔试过这个题
#include <iostream>
using namespace std;

class DataClock{
public:
    //Clock(int hour=0, int min=0, int sec=0);   //默认值???
    DataClock(int cYear, int cMonth, int cDate, int cHour, int cMin, int cSec);
    void showTime();
    bool ifLeapYear(int y);
    int howManyDays(int m, int y);
    //bool ifThirtyDays(int m);
    //bool ifThirtyOneDays(int m);

    void operator ++();//前置没有形参(可看做默认的规矩??)
    //void operator ++(int t);
private:
    int year;    int month;    int date;
    int hour;    int min;    int sec;
};
//DataClock.cpp实现
#include "DataClock.h"

DataClock::DataClock(int cYear, int cMonth, int cDate, int cHour, int cMin, int cSec){
    int thisMonDays = howManyDays(cMonth, cYear);  //这里带哦用方法对么??
    if(0<=cYear && 0<cMonth && cMonth<=12 && 0<cDate && cDate<=thisMonDays 
        && 0<=cHour && cHour<24 && 0<=cMin && 0<60 && 0<=cSec&&cSec<60)    {
            year=cYear;        month=cMonth;    date=cDate;
            hour = cHour;    min = cMin;        sec = cSec;
    }else
        cout << "time error!" <<endl;
}

void DataClock::showTime(){
    cout <<year<<"/"<<month<<"/"<<date<<"  " <<hour <<":" <<min << "  " <<sec<<"s" <<endl;
}

int DataClock::howManyDays(int m, int y){
    int days;
    if (m==1||m==3||m==5||m==7||m==8||m==10||m==12)
        days=31;
    else if(m!=2)
        days=30;
    else if(ifLeapYear(y))
        days=29;
    else
        days=28;

    return days;
}

bool DataClock::ifLeapYear(int year){
    if((year%100!=0 && year%4==0) || year%400==0)//如果尾数不是00,且能被4整除
            return true;
    else 
        return false;
}

void DataClock::operator ++(){
    ++sec;

    if (sec>=60){
        sec = sec-60;
        min++;
        if(min>=60){
            min = min-60;
            hour++;
            if(hour>=24){
                hour = hour-24; //这里相对 hour-24的优势是???
                date++;
                int thisMonDays = howManyDays(month, year);
                if(date> thisMonDays){
                    date = date-thisMonDays;
                    month++;
                    if(month>12){
                        month=month-12;
                        year++;
                    }
                }
            }
        }
    }
}
//年月日 时分秒 测试
void DataClockTest(){
    int y,m,d,h,min,s;
    cout << "请输入年月日时分秒共六个数:";
    cin >>y>>m>>d>> h >> min >>s;
    DataClock myTime(y, m, d, h, min, s);
    cout<<"输入时间是:";     
    myTime.showTime();
    ++myTime;
    cout << " 下一秒是:" ;    
    myTime.showTime();
}

 

 

 

posted on 2014-06-18 13:59  zhangxh_Doris  阅读(287)  评论(0编辑  收藏  举报