如果语句逻辑不正确

时间:2018-10-17 16:51:10

标签: c++ if-statement

我有这个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

在上述情况下,{BR}和项目1都设置为1,因此if应该为true。我们忽略了其他3个项目。

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

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

我的if逻辑有什么问题?

1 个答案:

答案 0 :(得分:3)

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

您的情况可能是这样的:

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将为true,因此(!included || x == 1)将始终为true。这就是我们想要的-如果不包括在内,则即使不检查x == 1也可以评估为true。

如果included = true为假,则!included为假,因此(!included || x == 1)的值将为x == 1。这又是我们想要的。如果包含我们,请依靠x == 1

相关问题