| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2243 人关注过本帖
标题:两个时间相加问题!
只看楼主 加入收藏
cjiang11034
Rank: 1
等 级:新手上路
帖 子:12
专家分:0
注 册:2009-10-12
结帖率:100%
收藏
已结贴  问题点数:10 回复次数:4 
两个时间相加问题!
当时间输入秒数为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;
}
搜索更多相关主题的帖子: 相加 时间 
2009-11-06 20:21
kspliusa
Rank: 3Rank: 3
等 级:论坛游侠
威 望:1
帖 子:98
专家分:178
注 册:2009-9-27
收藏
得分:10 
if(s>=0 && s<=59)    second = s;
else cout<<"the value of second is invalid!"<<endl;

}


加个等号!
2009-11-06 22:18
cookies5000
Rank: 2
等 级:论坛游民
帖 子:33
专家分:48
注 册:2009-10-25
收藏
得分:0 
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都没有定义。


2009-11-07 17:43
jstuchen
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2009-3-25
收藏
得分:0 
学习了
2009-11-09 09:03
wgd123pl
Rank: 2
来 自:湖北
等 级:论坛游民
帖 子:23
专家分:24
注 册:2008-8-16
收藏
得分:0 
我赞成楼上的说法
2009-11-09 16:08
快速回复:两个时间相加问题!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015668 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved