[英]Using modulus to find difference between 2 times?
我需要編寫一個程序,以 24 小時格式告訴我 2 次之間的差異。
因此,如果我輸入 22:30,它必須知道 22 = 小時和 30 = 分鍾。
此外,如果我輸入另一個時間(例如 23:50),它需要告訴我時差為 1 小時 20 分鍾。
我一直在玩它,但我真的不明白模數是如何工作的。
我試着寫:
到達時間=小時/100
小時 % 100 但我知道這沒有任何意義。
我只需要了解模數是如何工作的。
好的,然后讓我們考慮您已經將開始和停止時間作為小時和分鍾(都在同一天):
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
分鍾。
不使用模數,但您也可以使用<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
(此處可能實現)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.