[英]c program time conversion 24-h to 12-h
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.这是一个将 24 小时时间格式转换为 12 小时时间格式的程序,并且只需要一个四位整数作为输入。
ex.前任。 input = 0000 then output should be 00:00 am输入 = 0000 然后输出应该是 00:00 am
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;
}
With your code, if the hour = 0 and min = x, the output with be 00:xx am.使用您的代码,如果小时 = 0 且分钟 = x,则输出为 00:xx am。 With 12 hour time, there is no 00:xx am. 12 小时制,没有 00:xx am。 There is a 12:xx am, however.然而,有一个 12:xx am。 Therefore, you need to include another if statement if hour = 0.因此,如果小时 = 0,您需要包含另一个 if 语句。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.