首页 > 解决方案 > 为什么这个月比较代码不能正常工作?

问题描述

我已经完成了作业,几乎完成了,但是 C 程序中的这段代码阻止了我完成:

if ((month==1,3,5,7,8,10,12 && day>31)){
        printf("error only 31 days in that month");
        return 0;
    }
   else if (month==4,6,9,11 && day>30){
        printf("error only 30 days in that month");
        return 0;
      }
    else if (month==2 && leapyear && day>29){
        printf("error only 29 days in that month");
        return 0;
        }
        else if (month==2 && day>28){
            printf("error only 28 days in that month");
            return 0;
        }

我想说,如果月份是 1 并且输入大于 31,那么它会出错并停止,这就是问题所在。如果我在月份输入 4 并且日期是 34,它将打印第一条语句。有什么我可以做的吗?另外,请耐心等待;我对编程还是有点陌生​​。

标签: c

解决方案


在这样的情况下,你有一个简单的地图,其中一个不太长的连续序列中的整数进入(月份),然后出现一个数字(天数)。

您可以使用多个 IF 或使用建议的 OR 语法来执行此操作。

如果 ((月 == 1) || (月 == 3) || ... )

如果您的项目组非常少(尤其是不连续的)并且可能的输出非常少,那么上述方法将是最好的方法。第二个条件是真的(你只有 28/29、30 和 31),在我看来,第一个条件……只是勉强。

一般来说,我发现使用向量执行此操作更安全:

//        Vectors start at #0
int days[] = { 0,             31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// Correct data later
if (leapyear) {
    days[2]++;
}
if (day > days[month]) {
    printf("Month %d has only %d days\n", month, days[month]);
}

如果您有固定数量的不连续项目,则可以使用两个向量来执行此操作。这适用于任何分组,除非您有很多键或者可以想出一个简单的规则(当然,如果您想检查随机偶数日是一周中的哪一天,您不会输入所有 182 或 183 个偶数 -天数;你会检查它是偶数并使用模7)。

// I check all months except in summer.
// Keys holds the "question" (which month?), values the answer.
int keys   = {  1,  2,  3,  4,  5 ,       9, 10, 11, 12 };
int values = { 31, 28, 31, 30, 31,       30, 31, 30, 12 };
int i;
// I use 0 to indicate that the check does not apply (e.g. August)
days = 0;
for (i = 0; i < 12; i++) {
    if (month == keys[i]) {
        days = values[i];
    }
}
if (days != 0) {
    if (day > days) {
        printf("Month %d has only %d days\n", month, days);
    }
}

一种更好的方法(仅几个月)可能是指关节助记符

//            1st hand    knuckle    february   leap
int days = 31-((month<8)^(month%2))-(2==month)*(month-leapyear);
if (day > days) {
    printf("Month %d has only %d days\n", month, days);
}

推荐阅读