使用參考
#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:[email protected] V:NOTFOUND6O6
* @Date: 2023-02-23 19:44:59
* @LastEditors: Please set LastEditors
* @LastEditTime: 2023-03-03 15:19:55
* @FilePath: \WenkaiC\time_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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/545678.html
標籤:C++
上一篇:Problems caused by variable without initialization value
