gpt4 book ai didi

c++ - 使用逻辑与(&&)时,如何以编程方式查看 C++ 中未满足哪些条件?

转载 作者:行者123 更新时间:2023-11-30 05:03:34 26 4
gpt4 key购买 nike

我正在尝试高效推导出哪些条件导致 if 语句被程序忽略,而无需使用一系列 if 语句来分别验证每个变量的相对完整性。

这可能吗?

bool state = false;
int x = 0;
int y = 1;
int z = 3;

if(x == 0 && y == 1 && z == 2) {
// Do something...
state == true;
}

if(state == false) {

std::cout << "I did not execute the if statement because the following
conditions were not met: " << std::endl;

/*Find a way to make the program output that z != 3 stopped the
conditional from running without directly using if(z != 2)*/

}

最佳答案

您可以在 if 中的每个条件之间引入一个计数器作为“条件”,以查看运算符 && 的短路评估何时禁止执行后者条件:

int nrOfConditionFailing = 1;

if(x == 0 &&
nrOfConditionFailing++ && y == 1 &&
nrOfConditionFailing++ && z == 2) {
state = true;
}

if (!state) {
cout << "failed due to condition nr " << nrOfConditionFailing << endl;
}

如果你想检查所有条件,你不能在一个单独的 if 语句中完成;如果前一个条件的计算结果为假,运算符 && 的短路评估将阻止后一个条件甚至被检查/评估。

但是,您可以将这样的检查作为一个表达式,为每个不满足的条件在 unsigned int 中标记一个位:

int x = 1;
int y = 1;
int z = 3;

unsigned int c1 = !(x == 0);
unsigned int c2 = !(y == 1);
unsigned int c3 = !(z == 2);

unsigned int failures =
(c1 << 0)
| (c2 << 1)
| (c3 << 2);

if (failures) {
for(int i=0; i<3; i++) {
if (failures & (1 << i)) {
cout << "condition " << (i+1) << " failed." << endl;
}
}
}
else {
cout << "no failures." << endl;
}

关于c++ - 使用逻辑与(&&)时,如何以编程方式查看 C++ 中未满足哪些条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com