c - 确定一个月中的天数

标签 c

我收到了作为输入,我正在尝试以一种有效的方式验证输入。 范围是[0-99](0,4,8..被认为是闰年),范围是[1-12]和 范围 [1-31]。

验证日期的直接方法如下:

if( (Day<1u) || (Day>31u) ){
    /*error*/
}
else if ( (Month==4u) || (Month==6u) || (Month==9u) || (Month==11u) && (Day>30u) ){
    /*error*/
}
else if ( (Month==2u) && (Year % 4u == 0u) && (Day > 29u) ){
    /*error*/
}
else if ( (Month==2u) && (Year % 4u != 0u) && (Day > 28u) ){
    /*error*/
}
else
{
    /*valid*/
}

但它具有很高的复杂性。

查找表似乎是更好的选择。现在的问题是:

除了以下方法之外,是否还有更有效的方法来为这种情况创建表?

const int testTable[4][12] = {
    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

if( testTable[ Year % 4 ][ Month - 1 ] >= Day){
    /*valid*/
}
else{
    /*error*/
}

是否还有其他我没有看到的规则?

最佳答案

闰年需要一个维度,非闰年需要另一个维度:

int isleap(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int mthdays(int month, int year)
{
    static const int days[2][13] = {
        {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    };
    int leap = isleap(year);

    return days[leap][month];
}

The year range is [0-99] (0,4,8.. are considered leap years)

那么你的 isleap() 函数必须是:

int isleap(int year)
{
    return (year % 4 == 0);
}

month range [1-12]

使用:

{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

代替

{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

你可以避免 [ Month - 1 ]

关于c - 确定一个月中的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39463601/

相关文章:

c - 在特定值的转换工具中获取输出为 "-nan"

c - 为启动时运行的 linux 内核添加代码

c - 从另一个数组初始化 const 数组

指针和整数之间的比较

c - 读取错误设备驱动程序

C 程序 : Enter Number, 输出编号不同

c - C程序中的运算符值评估问题

c - 如何在 OS/X 上的 c 中使用 fflush

c - 访问特定内存地址

c - C语言从String中读取数据