Hey everyone. I've continuing to learn C++ and I've been set the 'challenge' of converting seconds to format as the Days,Minutes and Seconds.
For example: 31600000 = 365 days, 46 minutes, 40 seconds.
using namespace std;
const int hours_in_day = 24;
const int mins_in_hour = 60;
const int secs_to_min = 60;
long input_seconds;
cin >> input_seconds;
long seconds = input_seconds % secs_to_min;
long minutes = input_seconds / secs_to_min % mins_in_hour;
long days = input_seconds / secs_to_min / mins_in_hour / hours_in_day;
cout << input_seconds << " seconds = "
<< days << " days, "
<< minutes << " minutes, "
<< seconds << " seconds ";
return 0;
It works and comes up with the correct answer but after completing it I looked at how other people had tackled it and theirs was different. I'm wondering If I'm missing something.
Thanks, Dan.
The following code is what I use. int seconds = (totalSeconds % 60); int minutes = (totalSeconds % 3600) / 60; int hours = (totalSeconds % 86400) / 3600; int days = (totalSeconds % (86400 * 30)) / 86400; First line - We get the remainder of seconds when dividing by number of seconds in a minutes.
Converting seconds into time values in Excel With this idea, 1 day is equal to 86400 seconds. All you need to do is to divide the seconds value by 86400 to convert seconds into 1-day base.
One minute has 60 seconds, One hour has 60 minutes and one day has 24 hours. Thus, 80 x 60 x 24 = 86,400 seconds in a day.
I think is the challenge from Stephen Prata's book. I did it as follows:
#include <iostream>
using namespace std;
int main()
{
long input_seconds = 31600000;
const int cseconds_in_day = 86400;
const int cseconds_in_hour = 3600;
const int cseconds_in_minute = 60;
const int cseconds = 1;
long long days = input_seconds / cseconds_in_day;
long hours = (input_seconds % cseconds_in_day) / cseconds_in_hour;
long minutes = ((input_seconds % cseconds_in_day) % cseconds_in_hour) / cseconds_in_minute;
long seconds = (((input_seconds % cseconds_in_day) % cseconds_in_hour) % cseconds_in_minute) / cseconds;
cout << input_seconds << " seconds is " << days << " days, " << hours << " hours, " << minutes << " minutes, and " << seconds << " seconds.";
cin.get();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With