当前编程题:《某时间的前一秒和后一秒时间》

20 篇文章 1 订阅

【问题描述】

从键盘输入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;
}

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值