【问题描述】用结构体类型表示时间内容(时间以时分秒表示)输入一个时间数据,在输入一个秒数n(n<60),以h:m:s的形式输出过了n秒后的时间。(超过24点以0点开始)
【输入形式】输入的时间必须是以"时:分:秒"格式输入
【输出形式】同样以格式"时:分:秒"输出
【样例输入】
11:59:40
30
【样例输出】
12:0:10
#include <stdio.h>
//定义了一个结构体类型Time来表示时间
typedef struct{
int hour;
int minute;
int second;
}Time;
//定义了一个函数add_seconds来给一个Time对象添加秒数。
//最后在main函数中,程序读取输入的时间和秒数,调用add_seconds函数进行计算,然后输出结果。
Time add_seconds(Time t,int n)
{
t.second+=n;
if(t.second>=60)
{
t.minute+=1;
t.second-=60;
}
if(t.minute>=60)
{
t.hour+=1;
t.minute-=60;
}
if(t.hour>=24)
{
t.hour%=24;
}
return t;
}
int main()
{
Time t;
int n;
scanf("%d:%d:%d",&t.hour,&t.minute,&t.second);
scanf("%d",&n);
t=add_seconds(t,n);
printf("%d:%d:%d",t.hour,t.minute,t.second);
return 0;
}
当然,这道题可以不用结构体来做。
//暴力拆解法
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
char n;
cin >> a >> n >> b >> n >> c;
int N;
cin >> N;
if(c+N>=60)
{
if(b+1>=60)
{
if(a+1>=24) cout << 0 << n << 0 << n << c+N-60;
else cout << a+1 << n << 0 << n << c+N-60;
}
else cout << a << n << b+1 << n << c+N-60;
}
else cout << a << n << b << n << c+N;
return 0;
}
直接枚举加暴力AC通过