C++ Primer Plus Chapter 3 Exercise 4

c plus plusExercises 4 requires us to do some dimensional analysis. This can get confusing when trying to convert among the various quantities through programming techniques. I did do one thing different, I used constants that were already in seconds-per-quantity rather that exactly what the question asked. It seemed pointless going the book way as you would have to write code to convert the values to the seconds values when they are really manageable enough to make them constants themselves. Also, the question is inherently flawed, if you ask for a seconds value below a day, your data will be truncated. For instance, the book answer for 31600000 seconds is actually missing 17 hours of time from the display. This is significant. Nevertheless, here is what I was able to come up with:

4. Write a program that asks the user to enter the number of seconds as an integer value
(use type long) and that then displays the equivalent time in days, hours, minutes, and
seconds. Use symbolic constants to represent the number of hours in the day, the

number of minutes in an hour, and the number of seconds in a minute. The output should
look like this:
Enter the number of seconds: 31600000
31600000 seconds = 365 days, 46 minutes, 40 seconds

#include <iostream>

using namespace std;

// Required constants as per text, sort of
const int day = 86400;
const int hour = 3600;
const int minute = 60;

int main()
{

long seconds;
int days, minutes, hours, secondsLeft;

cout << "Enter the number of seconds: ";
cin >> seconds;

// Convert seconds to respective units
days = seconds / day;
hours = (seconds % day) / hour;
minutes = (seconds - days * day - hours * hour) / minute;
secondsLeft = seconds - days * day - hours * hour - minutes * minute;

cout << seconds << " Seconds = " << days << " days, " << hours << " hours, " << minutes << " minutes, "
<< secondsLeft << " seconds" << endl;

cin.get();
return 0;
}

Advertisements