Home > Software engineering >  Using modulus to find difference between 2 times?
Using modulus to find difference between 2 times?

Time:10-21

I need to write a program that will tell me the difference between 2 times, in the 24 hour format.

So if I enter 22:30, it has to know that 22 = hours and 30 = minutes.

Also if I enter another time (23:50 for example) it needs to tell me that the difference is 1 hour and 20 minutes.

I’ve been playing around with it but I don’t really understand how modulus works.

I tried writing :

Arrival time = hours/100

hours % 100 but I know that doesn’t make any sense.

CodePudding user response:

I just need to understand how modulus works.

Ok then lets consider you already have start and stop time as hour and minutes (both at the same day):

int start_h = 22;
int start_m = 30;
int stop_h = 23;
int stop_m = 50;

For easier caclulation of the difference we transform both to minutes:

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

So far so good, the difference is 100 minutes. To split that again in hours and minutes you can use the % operator:

 int diff_h = diff_m / 60;      // 80 / 60 = 1 (integer arithmetics)
 diff_m = diff_m % 60;          // 80 % 60 = 20

The last line is equivalent to

 diff_m = diff_m - (diff_m / 60) * 60;  // again: integer arithmetics

Because a % b is the remainder from dividing a by b. 60 fits into 80 once to make a full hour, and then there are 20 minutes left over.

CodePudding user response:

not using modulus, but you can also use the <chrono> library to find difference between 2 times

#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";
}

note: std::chrono::hh_mm_ss require c 20 (possible implementation here)

  • Related