注册 登录
编程论坛 C++教室

两个时间相加问题!

cjiang11034 发布于 2009-11-06 20:21, 2243 次点击
当时间输入秒数为1的时候出错,帮帮看哪里错啦!
#include <iostream>
using namespace std;

class Time{
public:
 Time(int h, int m, int s);
 Time  operator +(const Time &t2);
 friend ostream & operator << (ostream & os, const Time t);
private:
 int hour;
 int minute;
 int second;
};

Time::Time(int h, int m, int s)
{
 if(h>0 && h<=23) hour = h;
 else cout<<"the value of hour is invalid!"<<endl;

 if(m>0 && m<=59) minute = m;
 else cout<<"the value of minute is invalid!"<<endl;

 if(s>0 && s<=59)    second = s;
 else cout<<"the value of second is invalid!"<<endl;

}

Time  Time::operator +(const Time &t2)
{
 int hh,mm,ss;
 hh=mm=ss=0;
 if((ss=(second+t2.second)) >=60 ){
  ss-=60;
  ++minute;
 }
 if((mm=(minute+t2.minute)) >= 60){
  mm-=60;
  ++hour;
 }
 if((hh=(hour + t2.hour)) >= 24 ){
  hh-=24;
  cout<<"the sum is overflowed"<<endl;
 }
 return Time(hh,mm,ss);
}

ostream & operator<<(ostream & os, const Time t)
{
 os<<t.hour<<":"<<t.minute<<":"<<t.second;
 return os;
}

int main(void)
{
 Time t1(2,20,1), t2(4, 50, 59);
 cout<<(t1+t2)<<endl;
 system("pause");
 return 0;
}
4 回复
#2
kspliusa2009-11-06 22:18
if(s>=0 && s<=59)    second = s;
else cout<<"the value of second is invalid!"<<endl;

}


加个等号!
#3
cookies50002009-11-07 17:43
Time::Time(int h, int m, int s)
{
if(h>=0 && h<=23) hour = h;
else cout<<"the value of hour is invalid!"<<endl;

if(m>=0 && m<=59) minute = m;
else cout<<"the value of minute is invalid!"<<endl;

if(s>=0 && s<=59)    second = s;
else cout<<"the value of second is invalid!"<<endl;

}

不是1秒的问题,而是当h==0 || m==0 || s==0 时相应的hour\minute\second都没有定义。


#4
jstuchen2009-11-09 09:03
学习了
#5
wgd123pl2009-11-09 16:08
我赞成楼上的说法
1