0

Is there anything wrong with my code? It's a program that coverts 24-h time format to 12-h time format, and only takes a four-digit integer as input.

ex. input = 0000 then output should be 00:00 a.m.

When I submit my code to schools online judge, it doesn't accept all inputs, but I can't find out the problem.

#include <stdio.h>

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

    scanf("%02d%02d", &hour, &min);

    if (hour > 23 || min > 59)
    {
        return 1;
    }


    //check am pm
    if (hour >= 12)
    {
        morning = 1;

        if (hour > 12)
        {
            hour -= 12;
        }

    }
    else
    {
        morning = 0;
    }

    //print the result
    if (morning == 0)
    {
        printf("%02d:%02d a.m.", hour, min);
    }
    else
    {
        printf("%02d:%02d p.m.", hour, min);
    }

    return 0;
}
sky3691841
  • 11
  • 1
  • 1

1 Answers1

0

With your code, if the hour = 0 and min = x, the output with be 00:xx am. With 12 hour time, there is no 00:xx am. There is a 12:xx am, however. Therefore, you need to include another if statement if hour = 0.

#include <stdio.h>

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

    scanf("%02d%02d", &hour, &min);

    if (hour > 23 || min > 59)
    {
        return 1;
    }


    //check am pm
    if (hour >= 12)
    {
        morning = 1;

        if (hour > 12)
        {
            hour -= 12;
        }

    }
    //if input is 00xx
    if (hour == 0)
    {
    morning = 2;
    hour = hour + 12;
    }
    else
    {
        morning = 0;
    }

    //print the result
    if (morning == 2); 
    {
    printf("%02d:%02d a.m.\n", hour, min);
    }   
    if (morning == 0)
    {
        printf("%02d:%02d a.m.\n", hour, min);
    }
    if (morning == 1)
    {
        printf("%02d:%02d p.m.\n", hour, min);
    }

    return 0;
}