【问题标题】:Time Conversion in C [duplicate]C中的时间转换[重复]
【发布时间】:2021-08-10 02:56:20
【问题描述】:

谁能给我解释一下这段代码?我已经理解 if 和 else if 部分,但我被困在 else if 中的 else 部分。我不明白我们在这里减去了什么。时间格式为08:33:45AM(/PM)

char* timeConversion(char* s) {
    /*
     * Write your code here.
     */
    if (s[8]=='A')
    {
        if (s[0] =='1'&&s[1] =='2')
        {
            s[0] = '0';
            s[1] = '0';
        }
        s[8] = '\0';
    }
    else if (s[8] == 'P')
    {
        if (s[0]=='1' && s[1] =='2')
        {
            s[8] = '\0';
            return s;
        }

我们在这里减去了什么?

        s[0] = s[0]-'0'+'1';
        s[1] = s[1] - '0' +'2';
        s[8] = '\0';
    }
    else 
    {
        return "Error";
    }
    return s;
}

【问题讨论】:

标签: c


【解决方案1】:

我假设问题是将时间从 HH:MM:SSAM(PM)(12 小时)转换为 HH:MM:SS(24 小时)。如果是这样,您的代码在大多数输入中运行良好,但在某些情况下会失败。首先,让我们解释一下代码是如何工作的。

char* timeConversion(char* s) {
    // we check s[8] because in HH:MM:SSAM(PM) we can check whether
    // it is AM or PM by checking s[8] which is 'A' or 'P' respectively
    if (s[8]=='A')
    {
        // if it is 'AM' we don't need to change much except for these cases
        // 12:01:23AM is converted to 00:01:23
        // and that is what we are doing in the if part.
        if (s[0] =='1'&&s[1] =='2') 
        {
            s[0] = '0';
            s[1] = '0';
        }
        s[8] = '\0'; 
        // we are terminating the string at s[8], leaving only HH:MM:SS
    }
    else if (s[8] == 'P')
    {
        // 12:01:13PM is converted to 12:01:13. so we don't need to change 
        // anything if s[0] is '1' and s[1] is '2'.
        if (s[0]=='1' && s[1] =='2')
        {
            s[8] = '\0';
            return s;
        }
        // 04:24:56PM is changed to 16:24:56. so we need to add 1 to s[0]
        // and 2 to s[1] and that is done here.
        s[0] = s[0]-'0'+'1';
        s[1] = s[1] - '0' +'2';
        s[8] = '\0';
        // However this fails if the input is 08:23:55PM as the output will be 
        // 1::23:55 (ASCII value of '8' is 56 and ASCII value of ':' is 58)
        // and that is wrong answer. The correct answer is 20:23:55.
        // instead try changing first two characters to number and add 12 to it
        // and change the resultant number back to charecters.
    }
    else 
    {
        // if s[8] is neither 'A' nor 'P', then the input is wrong.
        return "Error";
    }
    return s;
}

你可以把 else if 部分的代码改成

int n = (s[0]-'0')*10 + (s[1]-'0');
n += 12;
s[0] = '0' + (n/10);
s[1] = '0' + (n%10);
s[8] = '\0';

【讨论】:

  • 这是一个很好的解释。由于假设,我怀疑这样称呼也很危险。我希望解析器读取整个字符串会更安全。
猜你喜欢
  • 2011-12-20
  • 1970-01-01
  • 2019-04-19
  • 2018-09-12
  • 2019-06-15
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
相关资源
最近更新 更多