C开关没有触发

时间:2015-07-06 20:32:12

标签: c

#include <stdio.h>

int main(void)
{
    char deci;
    int hours,min;

    printf("Enter a 12-hour time: ");
    scanf("%d:%d %c",&hours,&min,&deci);

    if(deci == 'PM'){
        switch(hours){
            case 1: printf("Equivalent 24-hour time: 13:%d",min); break;
            case 2: printf("Equivalent 24-hour time: 14:%d",min); break;
            case 3: printf("Equivalent 24-hour time: 15:%d",min); break;
            case 4: printf("Equivalent 24-hour time: 16:%d",min); break;
            case 5: printf("Equivalent 24-hour time: 17:%d",min); break;
            case 6: printf("Equivalent 24-hour time: 18:%d",min); break;
            case 7: printf("Equivalent 24-hour time: 19:%d",min); break;
            case 8: printf("Equivalent 24-hour time: 20:%d",min); break;
            case 9: printf("Equivalent 24-hour time: 21:%d",min); break;
            case 10: printf("Equivalent 24-hour time: 22:%d",min); break;
            case 11: printf("Equivalent 24-hour time: 23:%d",min); break;
            case 12: printf("Equivalent 24-hour time: 0:%d",min); break;
       }
    }
    else
        printf("Equivalent 24-hour time: %d:%d",hours,min);

    return 0;
}

预期行为:     输入12小时的时间:晚上9:11并打印此等效时间:21:11,我得到等效时间:9:11。为什么if()语句永远不会被评估为真?

2 个答案:

答案 0 :(得分:4)

您接受输入char deci。这是一个单一的角色。

更改条件:

if(deci=='P') // only P is able to identify 'PM'. you can work with this single char
{
  //
}

答案 1 :(得分:2)

您可能希望将deci读作字符串而不是单个字符。另请注意,您不能对字符串常量进行简单比较,并且字符串常量用双引号括起来,而不是单引号。

char deci[5];
int hours,min;

printf("Enter a 12-hour time: ");
scanf("%d:%d %s",&hours,&min,deci);

if(strcmp(deci,"PM") == 0) {
...

此外,即使使用该修复,输出也不会完全符合您的预期。这应该有效:

if(strcmp(deci,"PM") == 0) {
    if (hours == 12) {
        printf("Equivalent 24-hour time: 12:%d",min);
    } else {
        printf("Equivalent 24-hour time: %d:%d",hours+12,min);
    }
} else {
    if (hours == 12) {
        printf("Equivalent 24-hour time: 0:%d",min);
    } else {
        printf("Equivalent 24-hour time: %d:%d",hours,min);
    }
}