Subtracting large number from smaller without getting (-) answer

Please see line 14 for my question. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//This program takes two times (each in 12 hour cycle) and returns difference in Seconds.
int main(){	
int Hour, Minute, Second;
int Time1, Time2;

cout<<"Enter the first time in hours, minutes, and seconds:  ";
cin>>Hour>>Minute>>Second;
Time1 = Time_In_Seconds (Hour, Minute, Second);

cout<<"Enter the second time in hours, minutes, and seconds:  ";
cin>>Hour>>Minute>>Second;
Time2 = Time_In_Seconds (Hour, Minute, Second);

cout<<Time1- Time2<<endl;  //If Time2 is larger I get a negative number. Is there a way to get a correct answer regardless
//of which time is larger? I used an if statement to solve this, but I am curious if there is another smarter way to do it.
// Thanks for your help.

if (Time1 > Time2)
    cout<<"The time in seconds between two times is "<<Time1 - Time2<<endl;
else
    cout<<"The time in seconds between two times is "<<Time2 - Time1<<endl;
return 0;
}
int Time_In_Seconds (int hour, int min, int sec){
    int Time_in_Sec;
    Time_in_Sec = ((hour *60 *60) + (min *60) + sec);
    return Time_in_Sec;
}
Use abs().

Either #include <cstdlib> or write your own:

1
2
3
4
inline int abs( int n )
  {
  return (n < 0) ? -n : n;
  }
Duoas, Thank you. it works.
Topic archived. No new replies allowed.