C++数据验证问题

C++ Data Validation Issue

本文关键字:问题 验证 数据 C++      更新时间:2023-10-16
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"。