这是我的Cplex代码的一部分。我将PreReq定义为布尔变量,但是在约束条件下,我得到了PreReq的错误,即“表达式必须具有布尔类型”,我在做什么错呢?

IloBoolVarArray2 PreReq(env), CoRec(env), Offered(env);

//Constraint 6: if course d is taken and course c is its pre-req, then course c must be taken before d
IloExpr constraint6a(env);
IloExpr constraint6b(env);
IloExpr constraint6c(env);
IloExpr constraint6d(env);
for (c = 0; c < NumberOfCourses; c++) {
    for (d = 0; d < NumberOfCourses; d++) {
        if (PreReq[c][d] == 1 ) {
            for (s = 0; s < NumberOfSemesters; s++) {
                constraint6a += X[d][s];
                constraint6b += X[c][s];
                constraint6c += s*X[c][s];
                constraint6d += s*X[d][s];
            }
        }
    }
    mod.add(constraint6a <= constraint6b);
    mod.add(constraint6c <= constraint6d + (NumberOfSemesters)*(1 - onstraint6a) );
    constraint6a.end();
    constraint6b.end();
    constraint6c.end();
    constraint6d.end();
}

最佳答案

扩展Alex的答案:您的问题是您在混合约束和约束生成:在语句if ( PreReq[c][d] == 1 )中,operator==被重载以生成约束,该约束要求PreReq[c][d]取值1。因此,此表达式中的结果是IloConstraint类型,不是布尔类型(而是约束对象)。这就是为什么您收到错误消息的原因。相反,您想要在模型中添加一个约束,以防万一PreReq[c][d] is 1

所以您可能想要这样的东西:

for (d = 0; d < NumberOfCourses; d++) {
   for (s = 0; s < NumberOfSemesters; s++) {
      mod.add(IloIfThen(PreReq[c][d] == 1, constraint6a + X[d][s] <= constraint6b + X[c][s]));
      mod.add(IloIfThen(PreReq[c][d] == 0, constraint6a <= constraint6b));
   }
}


这就添加了约束的两个变体,其中只有一个会被激活(取决于PreReq[c][d]的值)。另请参见reference documentation of class IloIfThen

07-26 00:40