C中的复杂逻辑问题

时间:2013-02-08 19:22:08

标签: c logic

我无法在下面的代码块中思考它并确保它能够正常工作。

我有三个可能的输入词,称为A,B和C.

    //The following if-else block sets the variables TextA, TextB, and TextC to the    appropriate Supply Types.
if(strcmp(word,TextB)!=0 && strcmp(word,TextC)!=0 && i==1 && strcmp("",TextB)!=0) {
     strcpy(TextA,word);
}
else if(strcmp(word,TextA)!=0 && strcmp(word,TextC)!=0 && i==1 && strcmp("",TextC)!=0) {
  strcpy(TextB,word);
}
else if(strcmp(word,TextB)!=0 && strcmp(word,TextA)!=0 && i==1) {
  strcpy(TextC,word);
}

我想要发生的是,如果TextA中没有任何东西(第一次围绕AKA,当i = 1时;这一切都在循环中),然后将字写入TextA。但是,如果TextA中确实包含某些内容,请将单词写入TextB。如果TextB中有内容,请将TextC设置为word。我可以将这些单词重新复制到正确的位置,因为只有3个选项。

1 个答案:

答案 0 :(得分:1)

好的,你在循环中这样做,但是所有三个检查都有i==1,这意味着你只会进入其中一个块。 (当i为1时)。

通常情况下,当您在整个if / else if条件块中进行相同的检查(逻辑AND)时,您可以将其拉出块:

if (i == 1){
   //do all the other checks
}

但想想你是否真的想要这样做......根据你对你要解决的问题的描述,我认为你根本不需要检查i
如果你读过你在这个SO问题中所写的内容,那么代码实际上就是出现的:

  

如果TextA中没有任何内容,则将文字写入TextA
  如果TextA中确实包含某些内容,请将文字写入TextB
  如果TextB中有内容,请将TextC设置为word

所以遵循该逻辑的代码:

if (strlen(TextA) == 0)       // if TextA has nothing in it,
    strcpy(TextA, word);      // then write word to TextA
else if (strlen(TextB) == 0)  // else (if TextB doesn't have anything in it)
    strcpy(TextB, word);      // write word to TextB
else                          // if TextA and TextB already have something
    strcpy(TextC, word);      // then write word to TextC
相关问题