0

I am writing a program to convert 24-hour time to 12-hour time.
Output for 0:00 & 12:00 is faulty. Please refer to the code and the sample input and output.

#include <stdio.h>

int main(void)

     int hour;
     int min;

     printf("Enter a 24-hour time: ")
     scanf("%d:%d", &hour, &min);

     if (hour < 11)
          printf("Equivalent 12-hour time: %d:%d AM\n",
                     hour == 0 ? 12 : hour, min);

     else
         printf("Equivalent 12-hour time: %d:%d PM\n",
                     hour == 12 ? 12 : hour - 12, min);

     return 0;
}

When I input 12:00 ; the output is 12:0 PM When I input 0:00 ; the output is 12:0 AM

How can I fix this?

maaaaannn
  • 157
  • 1
  • 1
  • 5

1 Answers1

1

Need to use %2.2d:%2.2d or equivalent for format.

But, there's a logic bug: 11:45 is -01:45 PM

Change if (hour < 11) to if (hour < 12)

Here's the cleaned up code:

#include <stdio.h>

int
main(void)
{
    int hour;
    int min;

    printf("Enter a 24-hour time: ");
    scanf("%d:%d", &hour, &min);

    if (hour < 12)
        printf("Equivalent 12-hour time: %2.2d:%2.2d AM\n",
            hour == 0 ? 12 : hour, min);

    else
        printf("Equivalent 12-hour time: %2.2d:%2.2d PM\n",
            hour == 12 ? 12 : hour - 12, min);

    return 0;
}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48