Reputation: 5297
I made a Math game for my Kid (8 years old) and at some point i decided to show him how much time did he needed to answer to that question, so i decided to use the function time here.
I wrote the following program:
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
struct setClock{
int hour;
int minutes;
int seconds;
};
struct setClock currTime(void);
void timeCheck(struct setClock myClock[2]);
int main(void){
struct setClock myClock[2];
myClock[0] = currTime();
printf("Start Time: %d:%d:%d\n\n", myClock[0].hour, myClock[0].minutes, myClock[0].seconds );
sleep(5);
myClock[1] = currTime();
printf("End Time: %d:%d:%d\n", myClock[1].hour, myClock[1].minutes, myClock[1].seconds );
timeCheck(myClock);
return 0;
}
struct setClock currTime(void){
struct setClock ret;
struct tm *tm;
time_t myTime;
myTime=time(NULL);
tm=localtime(&myTime);
ret.hour = tm->tm_hour;
ret.minutes = tm->tm_min;
ret.seconds = tm->tm_sec;
return ret;
}
void timeCheck(struct setClock myClock[2]){
int hour;
int minute;
time_t end, start;
double diff;
start = (time_t)((myClock[0].hour * 60 + myClock[1].hour) * 60) ;
end = (time_t)((myClock[0].minutes * 60 + myClock[1].minutes) * 60) ;
if( end < start ){
end += 24 * 60 * 60 ;
}
diff = difftime(end, start);
hour = (int) diff / 3600;
minute = (int) diff % 3600 / 60;
printf("\n\n");
printf("The elapsed time is %d Hours - %d Minutes\n", hour, minute);
}
When i run it, i get different outputs like:
Start Time: 16:19:2
End Time: 16:19:7
The elapsed time is 3 Hours - 3 Minutes
Or:
Start Time: 16:19:14
End Time: 16:19:19
The elapsed time is 1 Hours - 1 Minutes
But the output should be:
The elapsed time is 0 Hours - 0 Minutes
I really don't know what's wrong with my timeCheck
function.
Any way if i fix it some how i need to expand it to print:
The elapsed time is 0 Hours - 0 Minutes - 5 Seconds.
Upvotes: 0
Views: 233
Reputation: 75062
start = (time_t)((myClock[0].hour * 60 + myClock[1].hour) * 60) ;
end = (time_t)((myClock[0].minutes * 60 + myClock[1].minutes) * 60) ;
This code seems nonsense. I think this should be
start = (time_t)((myClock[0].hour * 60 + myClock[0].minutes) * 60 + myClock[0].seconds) ;
end = (time_t)((myClock[1].hour * 60 + myClock[1].minutes) * 60 + myClock[1].seconds) ;
Then, have the function print what you want.
int second;
after int minute;
second = (int) diff % 60;
after minute = (int) diff % 3600 / 60;
printf("The elapsed time is %d Hours - %d Minutes - %d Seconds.\n", hour, minute, second);
Upvotes: 2