Seconds into minutes, hours, weeks and years.

I'm working on this program where you input a number in seconds, then its kicked back to you in however many units it makes up, so if you type 50, it will say 50 seconds, if you type 2000, it will say 33 minutes and 20 seconds and so on. If you typed in an exact number, like 60 seconds, it would kick back saying just 1 minute, or 60 minutes would kick back saying it was just an hour. I'm a little stuck, as I cant figure out how to get it to kick back the remainder of seconds from what ever number I input. For example, I'll type in 2000 seconds, and it will kick back saying 33 minutes and 2000 seconds.

#include <iostream>

using namespace std;

int main()
{
int s;
int m;
cout<<"Input a number in seconds please."<<endl;
cin >> s;
if (s<60)
{
cout << "This is "<<s<<" seconds." <<endl;
}
else if (s<3600)
{
m=s/60;
cout << "This is "<<m<<"minutes and "<<s<<"seconds." <<endl;
}
return 0;
}
@Nells7767

You never subtract the seconds used to acquire the minutes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using std::endl;
using std::cout;
using std::cin;

int main()
{
	int s;
	int m;
	cout<<"Input a number in seconds please."<<endl;
	cin >> s;
	if (s<60)
	{
		cout << "This is "<<s<<" seconds." <<endl;
	}
	else
	{
		m=s/60;
		s-=m*60;
		cout << "This is " << m << " minutes and " << s << " seconds." <<endl;
	}
	return 0;
}
Use an array to store how many seconds are in each unit then just walk through the array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

using namespace std;

struct TimeUnit {
    unsigned seconds;
    const char *name;
};
TimeUnit units[] {
    { 60*60*24*365,  "years" },
    { 60*60*24,  "days" },
    { 60*60,  "hours" },
    { 60, "minutes" },
    { 1, "seconds"}
};


int main()
{
    unsigned s;
    cout<<"Input a number in seconds please."<<endl;
    cin >> s;

    for (TimeUnit &unit : units) {
	if (s >= unit.seconds) {
	    cout << s/unit.seconds << ' ' << unit.name << ' ';
	    s %= unit.seconds;
	}
    }
    return 0;
}

Topic archived. No new replies allowed.