Add two durations stored as hours, minutes and seconds, carrying over correctly.
Solution
main.c
#include <stdio.h>
struct duration {
int h, m, s;
};
struct duration add(struct duration a, struct duration b) {
int total = (a.h + b.h) * 3600 + (a.m + b.m) * 60 + (a.s + b.s); /* work in seconds */
return (struct duration){total / 3600, total % 3600 / 60, total % 60};
}
int main(void) {
struct duration t = add((struct duration){1, 45, 50}, (struct duration){2, 20, 25});
printf("%02d:%02d:%02d\n", t.h, t.m, t.s);
return 0;
}
Output Verified by compiling and running
04:06:15
Converting to seconds and back makes the carrying automatic: 6350 + 8425 = 14775 s = 4 h 6 min 15 s. Compound literals pass the two times without named variables.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!