我需要撰寫一個程式,以 24 小時格式告訴我 2 次之間的差異。
因此,如果我輸入 22:30,它必須知道 22 = 小時和 30 = 分鐘。
此外,如果我輸入另一個時間(例如 23:50),它需要告訴我時差為 1 小時 20 分鐘。
我一直在玩它,但我真的不明白模數是如何作業的。
我試著寫:
到達時間=小時/100
小時 % 100 但我知道這沒有任何意義。
uj5u.com熱心網友回復:
我只需要了解模數是如何作業的。
好的,然后讓我們考慮您已經將開始和停止時間作為小時和分鐘(都在同一天):
int start_h = 22;
int start_m = 30;
int stop_h = 23;
int stop_m = 50;
為了更容易計算差異,我們將兩者都轉換為分鐘:
start_m = start_h * 60; // 30 (22*60) = 1350
stop_m = stop_h * 60; // 50 (23*60) = 1430
int diff_m = std::abs(stop_m - start_m); // 1430 - 1350 = 80
到目前為止一切順利,差別只有100幾分鐘。要將其再次拆分為小時和分鐘,您可以使用%運算子:
int diff_h = diff_m / 60; // 80 / 60 = 1 (integer arithmetics)
diff_m = diff_m % 60; // 80 % 60 = 20
最后一行相當于
diff_m = diff_m - (diff_m / 60) * 60; // again: integer arithmetics
因為a % b是從分割其余a通過b。60適合80一次,整整一個小時,然后20剩下幾分鐘。
uj5u.com熱心網友回復:
不使用模數,但您也可以使用<chrono>庫來查找 2 次之間的差異
#include <chrono>
#include <iostream>
int main(){
//using namespace std::literals::chrono_literals;
using namespace std::chrono;
//auto d = hh_mm_ss{(23h 50min)-(22h 30min)};
auto d = hh_mm_ss{ (hours{23} minutes{50}) - (hours{22} minutes{30}) };
std::cout << (d.is_negative() ? "negative " : "")
<< d.hours().count() << " hours "
<< d.minutes().count() << " minutes";
}
注意:std::chrono::hh_mm_ss需要c 20(此處可能實作)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/328483.html
