Thứ Năm, 8 tháng 3, 2012

Xây dựng lớp Time trong C++

Xây dựng một lớp Time mô tả các thông tin vê giờ, phút, giây.Lớp Time có các thành phần sau:
- Các thuộc tính mô tả giờ, phút, giây;
- Các hàm thành phần dùng để xác lập giá trị cho từng thành phần giờ, phút, giây(Có kiểm tra điều kiện giờ (0->23), phút(0->59), giây(0->59);
- Hàm thành phần setTime(int,int,int) để xác lập thời gian
- Hàm hiển thị giờ theo định dạng 24 tiếng (vd : 23:54:40);
- Hàm hiển thị giờ theo định dạng 12 tiếng( vd : 11:54:40 PM);
- Hàm tăngGiây()để tăng thời gian mỗi lần lên một giây. Chú ý các trường hợp tăng sang phút tiếp theo, tăng sang giờ tiếp theo,tăng sang ngày tiếp theo.
Viết chương trình chính khai báo một đối tượng thời gian là 23:59:58 và thực hiện tăng thời gian 5 giây đồng thời hiển thị thời gian cho mỗi lần tăng.

Trích từ:  http://kenhdaihoc.com/forum/showthread.php?t=2807

Code Tham khảo:
#include <iostream.h>
#include <conio.h>


class time
{
   private:
          int hour;
          int minute;
             int second;
          void incHour();
          void incMinute();
   public:
     void setTime(int,int=0,int=0);
     void setHour(int);
     void setMinute(int);
      void setSecond(int);
     void print12h();
     void print24h();
      void incSecond();
};


void time::incHour()
{
     hour++;
     if(hour==24) hour=0;


}
void time::incMinute()
{
      minute++;
     if(minute==60)
     {
      minute=0;
      incHour();
      }
}




void time::incSecond()
{
      second++;
     if(second==60)
       {
          second=0;
             incMinute();
       }




}
void time::setHour(int h)
{
  hour=(h>=0 &&h<24)? h:0;
}
void time::setMinute(int m)
{
  minute=(m>=0 &&m<60) ? m:0;
}
void time::setSecond(int s)
{
  second=(s>=0 &&s<60) ? s:0;
}
void time::setTime(int h,int m,int s)
{
    setHour(h);
    setMinute(m);
     setSecond(s);
}
void time::print24h()
{
  cout<<(hour<10 ? "0" : "")<<hour<<":"<<(minute <10 ? "0" : "")<<minute<<":";
  cout<<(second<10 ? "0" : "")<<second<<endl;
}
void time::print12h()
{
  cout<<(hour)<<":"<<(minute<10?"0":"")<<minute<<":";
  cout<<(second<10 ? "0":"")<<second<<(hour<12?" AM":"PM")<<endl;
}




void main()
{
  time t2;
  t2.setTime(23,59,58);
  t2.print12h();
  t2.print24h();
  for(int i=0;i<3;i++)
    {
      t2.incSecond();
      t2.print12h();
        t2.print24h();
    }


  getch();
}
Xem thêm: http://kenhdaihoc.com/forum/showthread.php?t=2807
Share:

0 nhận xét:

Đăng nhận xét