C程序时间转换

时间:2016-04-12 10:27:16

标签: c time

我在HackerRank中遇到了这个时间转换程序,我很惊讶程序在HackerRank中的编译方式(或者可能是我对C的误解)。

#include <stdio.h>

int main() {
    int hh, mm, ss;
    char tt[2];
    scanf("%d:%d:%d%s", &hh, &mm, &ss, tt);
    printf("%d\n", hh);
    if(strcmp(tt, "PM") == 0 && hh != 12) hh += 12;
    if(strcmp(tt, "AM") == 0 && hh == 12) hh = 0;
    printf("%02d:%02d:%02d", hh, mm, ss);
    return 0;
}

上面的程序,当我在计算机上运行时,使用MinGW 32位GCC编译器,我得到hh的值为零。

enter image description here

很好,我认为可能是编译器问题并在IDEONE中运行代码,结果相同。

enter image description here

但是当我用HackerRank运行相同的代码时,所有的测试用例都被传递了,我不知道,这是如何工作的?

enter image description here

我在这个阶段很困惑,我这样做了吗?

1 个答案:

答案 0 :(得分:1)

通过对tt中的空格进行更改以容纳 nul-terminatedating 字符,代码可以很好地转换为军事时间。通过在声明/定义期间将tt初始化为零所有元素,您可以确保tt在添加AM或PM时将被终止。 e.g。

#include <stdio.h>
#include <string.h>

int main (void) {

    int hh, mm, ss;
    char tt[3] = "";

    printf (" enter time in HH:MM:SS AM/PM: ");
    if (scanf ("%d:%d:%d %[^\n]%*c", &hh, &mm, &ss, tt) != 4) {
        fprintf (stderr, "error: invalid read of time.\n");
    }

    hh = (strcmp (tt, "PM") == 0 && hh != 12) ? hh + 12 : hh;
    if (strcmp (tt, "AM") == 0 && hh == 12) hh = 0;
    printf (" %02d:%02d:%02d\n\n", hh, mm, ss);

    return 0;
}

示例使用/输出

$ ./bin/tmread
 enter time in HH:MM:SS AM/PM: 11:59:04 PM
 23:59:04

仔细看看,如果您有任何问题,请告诉我。

相关问题