Converting seconds to hours and minutes and seconds

You've got a divide-by-zero problem here:

seconds % (hours*60);

hours is 0 by virtue of integer division.

hours = seconds/3600;

From what you're trying to do, you should consider conditional logic to print the minutes if the total number of seconds is greater than 3600. You'll also want to investigate similar logic in the next part of your print stream.

My C++ is rusty, so forgive if this isn't exactly valid syntax:

cout << (seconds > 3600 ? seconds % (hours*60) : seconds) << endl;

seconds/3600 is integer division, so for seconds < 3600, hours is 0, then things like seconds%(hours*3600) becomes seconds % 0, causing a division-by-zero.


Let's first get the logic right. Suppose you want to write 5000 seconds as x hours y minutes z seconds, such that all three are integers and neither y nor z is greater than 59. What do you do?

Well, you can first write it as q minutes z seconds, such that both are integers and z is not greater than 59. That's easy:

q = 5000 / 60 = 83  // integer division
z = 5000 % 60 = 20

So 5000 seconds is 83 minutes 20 seconds. Now how do you write 83 minutes into x hours y minutes, such that both are integers and y is no greater than 59? You do the same thing:

x = 83 / 60 = 1
y = 83 % 60 = 23

OK, let's generalize this:

int total, seconds, hours, minutes;
cin >> total;
minutes = total / 60;
seconds = total % 60;
hours = minutes / 60;
minutes = minutes % 60;
cout << total << " seconds is equivalent to " << hours << " hours " << minutes 
     << " minutes " << seconds << " seconds.\n" ;

Try this out instead, tested and works:

int seconds, hours, minutes;
cin >> seconds;
minutes = seconds / 60;
hours = minutes / 60;
cout << seconds << " seconds is equivalent to " << int(hours) << " hours " << int(minutes%60) 
     << " minutes " << int(seconds%60) << " seconds.";

Because minutes is seconds/60, dividing it by 60 again is equivalent to diving seconds by 3600, which is why it works.

Tags:

C++