Reputation: 11
I was doing the following programming exercise:
Write a program that asks the user to enter the number of seconds as an integer
value (use type long
, or, if available, long 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, 17 hours, 46 minutes, 40 seconds
So I wrote this (in Microsoft Visual Studio 2015):
#include "stdafx.h"
#include iostream
int main()
{
using namespace std;
const int sec_per_min = 60;
const int min_per_hr = 60;
const int hr_per_day = 24;
cout << "Enter numbers of second: ";
long long seconds;
cin >> seconds;
int day, hr, min, sec;
day = seconds / (sec_per_min * min_per_hr * hr_per_day);
hr = (seconds - day * hr_per_day * min_per_hr * sec_per_min) / (sec_per_min * min_per_hr);
sec = seconds % sec_per_min;
min = (seconds - sec) / sec_per_min % min_per_hr;
cout << seconds << " seconds = ";
cout << day << " days, ";
cout << hr << " hours, ";
cout << min << " minutes, ";
cout << sec << " seconds.";
return 0;
}
It produced the correct outcome.
But I was wondering if there's better statements for day
, hr
, min
, sec
?
Upvotes: 0
Views: 3333
Reputation: 118292
I would've done the following. I think it's much clearer:
auto n=seconds;
sec = n % sec_per_min;
n /= sec_per_min;
min = n % min_per_hr;
n /= min_per_hr;
hr = n % hr_per_day;
n /= hr_per_day;
day = n;
Upvotes: 4