Question

I know you're supposed to post code of what you have started when asking questions, but honestly I am completely lost. I am reading a book on C++ to learn (I'm self taught), the book is Sams C++ Primer Plus. I have recently just finished the chapter on type conversions and type casts. Well, I was interested in trying to make the program that converts seconds to days/minutes/seconds. It's a very simple application. I could code the application perfectly, but for some reason the math stumps me. I need help with this, or at least starting the variables and such. Thanks.

Also, I'm sure I am supposed to use the modulo (in C++ modulus) somewhere within the program.

The output of the program is supposed to be similar to this:

"Enter the number of seconds: SECONDS"

"SECONDS seconds = 364 days, 46 minutes, 40 seconds.

The actual values in the output don't matter as long as the conversion is correct.

Was it helpful?

Solution

const int SECSPERDAY=84600;
const int SECSPERHOUR=3600;
const int SECSPERMIN=60;

int days=SECONDS/SECSPERDAY;
int hours=(SECONDS-(days*SECSPERDAY))/SECSPERHOUR;
int mins=(SECONDS-(days*SECSPERDAY)-(hours*SECSPERHOUR))/SECSPERMIN;
int secs=SECONDS%SECSPERMIN;

OTHER TIPS

As your task is connected to type conversions and -casts I would suggest the learning outcome is that dividing with integers drops the remainder and you can get the remainder by modulu operation.

therefor you can use (given SECONDS is the input)

int sec   = SECONDS % 60;
int min   = (SECONDS / 60) % 60;
int hours = (SECONDS / (60 * 60)) % 24;
int days  = (SECONDS / (60 * 60 * 24) % 365;
int years = (SECONDS / (60 * 60 * 24 * 365);

I did not use constants to show the direct depedencies even if this is considered bad practice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top