我的代码是:
if(seatingChart[row][seat][incorrectQuestion].question==seatingChart[compareRow][compareSeat][compareIncorrectQuestion].question&&seatingChart[row][seat][incorrectQuestion].answerChoice==seatingChart[compareRow][compareSeat][compareIncorrectQuestion].answerChoice||seatingChart[row][seat][incorrectQuestion].answerChoice==compareAnswerChoice)
我使用的数据结构是:
struct incorrect
{
unsigned int question;
unsigned int answerChoice
};
compareAnswerChoice返回无符号整数值。实际上,参数中的每个单值都是无符号整数值,但最终后的参数或似乎打破了if语句。没有值是负数,它们从字符(小写和大写)转换为1到26之间的无符号整数。编译没有返回任何错误,矢量中的参数指的是它们的正确位置。
当我只使用:
if (seatingChart[row][seat][incorrectQuestion].answerChoice ==
compareAnswerChoice)
以下代码工作正常,但是当我添加前if语句中的任何前部参数时,内部代码无效。
我明白我做错了什么,但我不知道究竟是什么,所以我无法纠正自己。有人能告诉我这些参数有什么问题吗?
答案 0 :(得分:1)
在C ++中,运算符&&
比运算符||
(14)更高(13)precedence。您需要在if
声明中使用括号。
@ user3093536使用调试器很容易调试这样的东西。创建具有已知值的条件,并测试if()
语句如何与运算符&&
和||
一起使用。进入代码。
答案 1 :(得分:1)
让我们先来清理一下,这样我们就可以看到发生了什么:
unsigned int question =
seatingChart[row][seat][incorrectQuestion].question;
unsigned int answer =
seatingChart[row][seat][incorrectQuestion].answerChoice;
unsigned int compare_question =
seatingChart[compareRow][compareSeat][compareIncorrectQuestion].question;
unsigned int compare_answer =
seatingChart[compareRow][compareSeat][compareIncorrectQuestion].answerChoice;
if (question == compare_question && answer == compare_answer ||
answer == compareAnswerChoice)
逻辑AND运算符&&
的优先级高于逻辑OR运算符||
,因此这相当于:
if ((question == compare_question && answer == compare_answer) ||
answer == compareAnswerChoice)
你可能想要的是:
if (question == compare_question &&
(answer == compare_answer || answer == compareAnswerChoice))
答案 2 :(得分:0)
我认为您的问题在于&&
运算符的优先级高于||
。尝试添加像
if(seatingChart[row][seat][incorrectQuestion].question==seatingChart[compareRow][compareSeat][compareIncorrectQuestion].question &&
(seatingChart[row][seat][incorrectQuestion].answerChoice==seatingChart[compareRow][compareSeat][compareIncorrectQuestion].answerChoice
|| seatingChart[row][seat][incorrectQuestion].answerChoice==compareAnswerChoice))