Time calculation problem

Hi! I'm a beginner in writing C++, I've come to this forum to ask any who is willing to read this a problem I've had on my program.

Whenever I run this program I wrote it never calculates the "seconds" into anything exceeding the 3600 value. Everything is fine on the "minutes" but on the "hours" and "days" it doesn't do it.

-Thank you,
Reekoh

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
#include <iostream>
using namespace std;

int main(){
        int seconds,
        minutes,
        hours,
        days;

        cout << "Time calculator" << endl;
        cout << "Enter any number for seconds: ";
        cin >> seconds;
        cout << endl;

        minutes = seconds / 60;
        hours = seconds / 3600;
        days = seconds / 86400;


        if (seconds >= 60)
        cout << minutes << " minutes" << endl;
        else if (seconds >= 3600)
        cout << hours<< " hours" << endl;
        else if (seconds >= 86400)
        cout << days << " days" << endl;

return 0;
}
Here I show you your actual control flow:
1
2
3
if (seconds >= 60)

else /*if seconds < 60*/ if (seconds >= 3600)
As you can see, second condition is checked only if seconds < 60 and of course always false.
Easiest way to fix it for you is to change order of checking to from largest to smalles, i.e. from days to minutes
Note the else ifs. If you enter a value >= 60, minutes will display because the expression is true. The else part of that if will not execute because the condition was true.

I suspect what you wanted was:
1
2
3
4
5
6
    if (seconds >= 60)
        cout << minutes << " minutes" << endl;
    if (seconds >= 3600)
        cout << hours<< " hours" << endl;
    if (seconds >= 86400)
        cout << days << " days" << endl;


See the difference?
oh thanks!, both of your answers really helped me understand what I was doing wrong.
I fixed my if else statement. Turns out I just needed to fix my if else order since the moment it runs through it the first statement is always true.

Thank you both,
Topic archived. No new replies allowed.