我收到了年、月和日作为输入,我正在尝试以一种有效的方式验证输入。 年范围是[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/