#使用引用 #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 + se ...
使用引用
#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;
}