C++数据验证问题
C++ Data Validation Issue
if (month > 0 && month <= 12)
if (day > 0 && day <= checkDays(month, year))
if (year >= 1752 || year <= 9999)
if((month != 12 && day != 31 && year != 9999))
return true;
else return false;
else return false;
else return false;
else return false;
我的值 month = 12,天 = 31,年份 = 2008,数据验证在最后一部分失败,但我无法弄清楚原因。
你的第一年条件在你想要的时候使用 OR;你的第二年条件与我怀疑你想要的完全相反。
您还有一个操作顺序错误:在验证月份和年份之前,您无法检查日期(假设checkDays
所做的是为特定(月,年)对提供最大天数;如果是这样,则应将其重命名为days_in_month
)。
最后,如果编写为一系列 if-fail-return-false 条件而不进行任何嵌套,则此类代码通常更容易阅读。 这样:
// Year range supported is [1752, 9999].
// (Gregorian calendar introduced in 1752 in Great Britain.)
if (year < 1752 || year > 9999)
return false;
// Valid month numbers in [1, 12].
if (month < 1 || month > 12)
return false;
// Valid day numbers in [1, n] where n depends on month and year.
if (day < 1 || day > checkDays(month, year))
return false;
// 9999-12-31 is invalid (used as a sentinel value?)
if (year == 9999 && month == 12 && day == 31)
return false;
return true;
顺便说一下,现在的长人想说一下你的年上限。
我发现用"找到假的东西并返回"来写这些东西几乎总是更容易。所以:
if (month < 1 || month > 12) return false;
if (day < 1 || day > 31) return false;
if (year < 1752 || year > 9999) return false;
if (month == 12 && day == 31 && year == 9999) return false;
// If we get here, everything is fine, so return true.
return true;
当然,您可能应该根据月份来检查day
:
int daysInMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month < 1 || month > 12) return false; // Must do this before checking day!
int daysThisMonth = daysInMonth[month];
// Check for leapyear.
if (month == 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
{
daysThisMonth = 29;
}
if (month != 2 && day < 1 || day > daysThisMonth) return false;
...
有点猜测,因为我不太清楚你的函数应该做什么,但在这里。
仅当月份不是 12 且日不是 31 且年份不是 9999 时,month != 12 && day != 31 && year != 9999
才返回 true。
因此,对于您的输入,它是:
month != 12 && day != 31 && year != 9999
=> false && false && true
=> false
你不想要:
month != 12 || day != 31 || year != 9999
如果月份不是 12 或日期不是 31 或年份不是 9999,则返回 true。
一种等效的,但可能更容易理解的编写方式:
!(month == 12 && day == 31 && year == 9999)
所以这就是"如果月份是 12,第 31 天和 9999 年,则返回 false"。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- C++卡验证问题
- 在C++中验证for循环的问题
- 使用OpenSSL的SHA 512 HMAC消息身份验证的问题
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- 库库尔身份验证问题
- 刽子手游戏的验证问题
- 程序不输出正确的标准偏差.另外,验证问题
- C++信用卡验证问题
- C++数据验证问题
- 验证我的超类或基类是宏或模板声称的那个类时出现问题
- if字符串验证循环出现问题
- c++字符验证问题
- Visual在c++中验证电子邮件有问题
- 验证二叉树的小问题
- C++SDL代码::块:在头文件中声明指向全局可验证性的指针,同时避免多个包含问题
- 一遍又一遍地验证文件时遇到问题