views:

449

answers:

2

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.

A: 

One of the things about programming is that there is never just one way to do something. In fact if I were to set my mind to it, I might be able to come up with a dozen completely different ways to accomplish this. You're not missing anything if your code meets requirements.

For your amusement, here's a way to format up hours:minutes:seconds under Windows (elapsed is a double & represents number of seconds elapsed since... something)

sprintf_s<bufSize>(buf, "%01.0f:%02.0f:%02.2f", floor(elapsed/3600.0), floor(fmod(elapsed,3600.0)/60.0), fmod(elapsed,60.0));
John Dibling
A: 

For example: 31600000 = 365 days, 46 minutes, 40 seconds.

Really?

$ bc
365*24*60*60 + 46*60 + 40
31538800

365*24*60*60 + 1066*60 + 40
31600000

Did you mean "convert the input into days, hours, minutes and seconds, and then discard the hours" or "convert the input into days, total minutes within a day (i.e. can be more than 60), and seconds"?

In the second case I think you should replace the instruction for minutes with

long minutes = input_seconds / secs_to_min % (mins_in_hour * hours_in_day);
Federico Ramponi
Yeah I meant to discard the hours however thanks for the reply.
Dan