+ 10

[Solved] Trouble with Military Time

I have been trying to solve the military challenge in C. I wrote this code and it fails on test 3 and 5. I can not figure out what is wrong with it. #include <stdio.h> #include <string.h> int hour, min; char TOD[2]; //Time of Day int main() { scanf("%d:%d %s", &hour, &min, TOD); if(strcmp(TOD, "PM") == 0 && hour != 12){ hour+=12; } if(strcmp(TOD, "AM") == 0 && hour == 12){ hour = 0; } if(min == 0){ printf("%d:%d0", hour, min); } else{ printf("%d:%d", hour, min); } return 0; } https://code.sololearn.com/choEXv1Rs1LC/?ref=app

14th Apr 2021, 10:54 AM
Brain & Bones
Brain & Bones - avatar
4 Answers
+ 3
Coder Kitten That was it. Thank you.
14th Apr 2021, 12:35 PM
Brain & Bones
Brain & Bones - avatar
0
Nc
17th Apr 2021, 1:48 PM
Md Habibulla Hosem
Md Habibulla Hosem - avatar
0
In military time, leading zeros are usually added to hours and minutes less than 10. To ensure proper formatting, add zero padding when printing the time. When converting from AM to 24-hour format, if the input is 12:00 AM, the correct output should be 00:00. Currently, your code sets the hour to 0, but you should also handle zero-padding for the hour. https://www.screenmirroring.onl/how-to-play-pubg-on-smart-tv-using-screen-mirroring/ #include <stdio.h> #include <string.h> int hour, min; char TOD[2]; //Time of Day int main() { scanf("%d:%d %s", &hour, &min, TOD); if (strcmp(TOD, "PM") == 0 && hour != 12) { hour += 12; } if (strcmp(TOD, "AM") == 0 && hour == 12) { hour = 0; } if (hour == 0) { printf("00:%02d", min); // Zero-padding for hour } else { printf("%02d:%02d", hour, min); // Zero-padding for both hour and minute } return 0; }
7th Aug 2023, 7:19 AM
manjira
0
In your code, converting time to military format mostly looks good, but there's a small mistake that you made in this code. A mistake is how you're handling minutes. When minutes are zero, you're printing an extra zero at the end, which isn't needed. You can try this below code that helps you to fix your mistake and run: https://www.publix-passport.com/ #include <stdio.h> #include <string.h> int main() { int hour, min; char TOD[3]; //Time of Day scanf("%d:%d %s", &hour, &min, TOD); if(strcmp(TOD, "PM") == 0 && hour != 12){ hour += 12; } if(strcmp(TOD, "AM") == 0 && hour == 12){ hour = 0; } printf("%02d:%02d", hour, min); // This will print the hour and min with leading zeros if needed return 0; } I hope my suggestion will be helpful for everyone.
21st Mar 2024, 11:44 AM
Jamie Cordeiro