如果语句逻辑不正确

If Statement logic is not correct

本文关键字:不正确 语句 如果      更新时间:2023-10-16

我有这个if语句,但它不起作用:

if (pEntry->GetStudentMaterialStudyPoint(StudentAssign::kBibleReading) == 1 &&
(pEntry->GetStudentMaterialStudyPoint(StudentAssign::kItem1) == 1 && LOBYTE(LOWORD(pEntry->GetStudentAssignFlags()))) &&
(pEntry->GetStudentMaterialStudyPoint(StudentAssign::kItem2) == 1 && HIBYTE(LOWORD(pEntry->GetStudentAssignFlags()))) &&
(pEntry->GetStudentMaterialStudyPoint(StudentAssign::kItem3) == 1 && LOBYTE(HIWORD(pEntry->GetStudentAssignFlags()))) &&
(pEntry->GetStudentMaterialStudyPoint(StudentAssign::kItem4) == 1 && HIBYTE(HIWORD(pEntry->GetStudentAssignFlags()))))
{
MWBValidationErrorStruct errorMWBValidation;
errorMWBValidation.iDateIndex = iDateIndex;
errorMWBValidation.datMeeting = pEntry->GetMeetingDate();
errorMWBValidation.eValidationErrorType = CChristianLifeMinistryDefines::MWBValidationErrorType::MaterialStudyPoints;
m_listValidationErrors.push_back(errorMWBValidation);
}

}

我试图找出是否所有项目的值都为 1。第一项(圣经阅读(将始终被检查。但是,如果项目1到4被"包括在内",才需要检查它们。这就是LOBYTE(LOWORD(pEntry->GetStudentAssignFlags()))的目的。

所以

Bible Reading - 1
Item 1 - 1
Item 2 - 1 - Not included
Item 3 - 1 - Not included
Item 4 - 1 - Not included

在上述方案中,应trueif,因为 BR 和项目 1 都设置为 1。我们忽略其他 3 项。

Bible Reading - 1
Item 1 - 2
Item 2 - 3
Item 3 - 1 - Not included
Item 4 - 1 - Not included

在上述情况下,if应返回false,因为所有值都不是 1,并且我们忽略了最后两项。

我的if逻辑有什么问题?

您应该使用(!included || x == 1)来忽略检查未包含的项目。由于短路,如果included为假,您甚至不会检查OR的另一侧,这正是您想要的。

您的 if 可能如下所示:

if (pEntry->GetStudentMaterialStudyPoint(StudentAssign::kBibleReading) == 1 &&
(!LOBYTE(LOWORD(pEntry->GetStudentAssignFlags())) || pEntry->GetStudentMaterialStudyPoint(StudentAssign::kItem1) == 1) &&
...

这可能有点令人困惑,所以让我们做一个真值表......

included | x | !included | x == 1 | (!included || x == 1)
------------------------------------------------------
false   | 3 |   true    |  false |         true         
true    | 3 |   false   |  false |         false       
true    | 1 |   false   |  true  |         true 

如果included = false,那么!included就是真的,所以(!included || x == 1)永远是真的。这就是我们想要的——如果我们不包括在内,只需评估为 true,甚至不检查x == 1

如果included = true,则!included为假,因此(!included || x == 1)的值将是x == 1的任何值。这又是我们想要的。如果我们包括在内,那么取决于x == 1.