使用引用
#include <iostream>
using namespace std;
struct Time{
int h;
int m;
int s;
};
void timeCompute(Time &t, int sec){ //引用作为形参
t.m = t.m + (t.s + sec)/60; //分钟的进位
t.s = (t.s + sec)%60; //秒数位计算后剩余的时间
t.h = t.h + t.m/60; //小时的进位
t.m = t.m%60; //分钟位计算后剩余的时间
t.h = t.h%24; //小时位取余实现24小时制
}
int main(){
int repeat,sec; //重复次数
cin >> repeat;
struct Time t; //创建一个time类型的结构体 t
for(int i = 0; i < repeat; i++){
scanf("%d:%d:%d", &t.h, &t.m, &t.s); //存入结构体 h m s
cin >> sec; //要度过的秒数
timeCompute(t,sec);
cout << t.h << ":" << t.m << ":" << t.s << endl;
}
return 0;
}
复杂且笨的写法
/*
* @Author: DEFT:errornotfound@qq.com V:NOTFOUND6O6
* @Date: 2023-02-23 19:44:59
* @LastEditors: Please set LastEditors
* @LastEditTime: 2023-03-03 15:19:55
* @FilePath: WenkaiC ime_conversion.cpp
* @Description:
*
* Copyright (c) 2023 by 1zPeasy, All Rights Reserved.
*/
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
int repeat,hour,minute,second,spend_second,add_minute;
cin >> repeat; //输入重复次数
for (int i = 0; i < repeat; i++)
{
int num_scanned = scanf("%d:%d:%d", &hour, &minute, &second); //输入时间
cin >> spend_second; //输入要度过的秒数
second = second + spend_second;
add_minute = second/60; //计算秒数加完到底是要进位多少分钟
second = second%60; //计算进位分钟后还剩多少秒
minute = minute + add_minute; //进位后的分钟
//判断minute是否需要进位
if (minute >=60) //如果更新后的分钟大于等于60
{
hour = hour + minute/60; //计算更新后的hour
minute = minute % 60; //分钟数进位后minute还剩多少分钟
}
//判断hour是否需要进位
if (hour >= 24) //如果进位后小时数大于=24
{
hour = hour % 24; //更新后的小时数
}
cout << "time: " << hour << ":" << minute << ":" << second << endl;
//判断scanf返回值用来处理错误
if (num_scanned != 3) {
}
}
return 0;
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 »
C++时间对秒数的运算