convert the time sec to HH:MM:SS

Dec 10, 2011 at 8:33pm
hi

I need to convert the time given in seconds (time_target) for 3 variables (hour, min, sec)
I have a problem with the second of the program's output.
I would appreciate your help.the program written in C. thanks.


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 <stdio.h>

const int ONE_HOUR = 60 * 60;
const int ONE_MINUE = 60;

int hour;
int min;
int sec;

int time_target=4600;


int main()
{

hour=time_target/ONE_HOUR;
time_target-=hour*ONE_HOUR;
min=time_target/ONE_MINUE;
time_target-=min*ONE_HOUR;
sec=time_target;

printf("%d:%d:%d\n",hour,min,sec);
return 0;
} 


} 


output: 1:16:-56600
Last edited on Dec 10, 2011 at 10:40pm
Dec 10, 2011 at 9:27pm
Look at what you substract from time after calculating the number of minutes. Does that look right to you? PS: MINUE should be MINUTE? Also, hour/min/sec and time_target should be local to main. It would also be preferable to read the value for time_target with something like scanf instead of setting it to a constant value.
Dec 10, 2011 at 10:12pm
try this:
1
2
3
4
5
6
7
8
9
10
11
12
#define HOUR 3600
#define MIN 60

int main(){
    int time_target=4600;
    int hour=time_target/HOUR;
    int second=time_target % HOUR;
    int minute=second/MIN;
    int second %= MIN;
    printf("%.2d:%.2d:%.2d"),hour,minute,second);
    return 0;
}
Dec 10, 2011 at 10:20pm
Thank you for quick reply, now saw the error of calculation.
time_target-=min*ONE_HOUR; -> fix time_target-=min*ONE_MINUE;
Topic archived. No new replies allowed.