【问题描述】
从键盘输入24小时制的某个时间,计算并输出其前一秒和后一秒的时间。
【输入形式】
从键盘输入24小时制的某个时间,格式为:hh:mm:ss。
【输出形式】
输出2行,第1行为输入时间的前1秒时间,第2行为输入时间的后1秒时间,格式为:hh:mm:ss。
【样例输入1】
09:59:59
【样例输出1】
09:59:58
10:00:00
【样例输入2】
00:00:00
【样例输出2】
23:59:59
00:00:01
解体思路与易错分析:
这道题的难点就在于就输入的时间的分割,以及就数据的处理问题,当然方法有很多,这里只讲我的思路,
我会用一个string来储存一行的数据(当然你这里也可以用char数组来储存,这样也可以省略了后面的将string转化为int),然后在分割字符串,最后在将分割的字符串转化为数字(int)在进行过处理,更加详细的说明请看https://blog.csdn.net/qq_41682681/article/details/80772469
我觉得这样挺麻烦的,如果你有好的方法可以给我分享一下(这里多谢),剩下的就是if-else语句来判断情况并分类讨论,最后是就是有关格式输出的问题可以采用iomanip中的setw()于setfill()函数同时这要注意于setprecision()的区别,setfill()是只对后面紧跟的输出才有作用,而setprecision()则是黏性的对后面的全部都有作用
下面附上我的代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main()
{
int h,m,s;
string in,hh,mm,ss;
getline(cin,in);
hh = in.substr(0,2);
mm = in.substr(3,2);
ss = in.substr(6,2);
h = atoi(hh.c_str());
m = atoi(mm.c_str());
s = atoi(ss.c_str());
if(s-1<0)
{
if(m-1<0)
{
if(h-1<0)
{
cout << 23 << ":" << 59<<":" << 59<<endl;
}
else
{
cout << setw(2)<<setfill('0') <<h-1 << ":" << 59<<":" << 59<<endl;
}
}
else
{
cout << setw(2)<<setfill('0') <<h << ":" << setw(2)<<setfill('0')<< m-1<<":" << 59<<endl;
}
}
else
{
cout << setw(2)<<setfill('0') <<h << ":" << setw(2)<<setfill('0')<< m<<":" << setw(2)<<setfill('0')<< s-1<<endl;
}
if(s+1>=60)
{
if(m+1>=60)
{
if(h+1>23)
{
cout << "00" << ":" << "00"<<":" << "00"<<endl;
}
else
{
cout << setw(2)<<setfill('0') <<h+1 << ":" << "00"<<":" << "00"<<endl;
}
}
else
{
cout << setw(2)<<setfill('0') <<h << ":" << setw(2)<<setfill('0')<<m+1<<":" << "00"<<endl;
}
}
else
{
cout << setw(2)<<setfill('0') <<h << ":" << setw(2)<<setfill('0')<< m<<":" << setw(2)<<setfill('0')<< s+1<<endl;
}
return 0;
}