简体   繁体   English

如何在 for 循环中每次迭代只执行一次“if”语句?

[英]How can I execute an 'if' statement only once per iteration in a for loop?

Assuming there are no duplicate words in either list, I would like to compare the words of listA with the words in listB.假设两个列表中都没有重复的单词,我想将 listA 中的单词与 listB 中的单词进行比较。 If there is a match, I want to print the word that matches and compare the next 'n' words in listB to see if there is a match.如果匹配,我想打印匹配的单词并比较 listB 中的下一个“n”个单词以查看是否匹配。 Likewise, if there is no match, (ie once I reach the last word in listA), I want to print the word that could not be found and compare the next 'n' words in listB to see if there is a match.同样,如果没有匹配项(即,一旦我到达 listA 中的最后一个单词),我想打印找不到的单词并比较 listB 中的下一个“n”个单词,看看是否有匹配项。

I am stuck on how I should implement statements (if, break, continue) in my for loop so that it meets the specifications listed above.我被困在如何在我的 for 循环中实现语句(if、break、continue),以使其符合上面列出的规范。 When I run the code below, it only prints the instance in which there is a match, but it does not print anything at all if there is no match.当我运行下面的代码时,它只打印有匹配的实例,但如果没有匹配,它根本不打印任何东西。

alineno & blineno refer to current line number in the arrays aline & bline where the words are stored alineno & blineno指 arrays aline aline & bline中存储单词的当前行号

 // index through listA
 for(i = 0; i < alineno; i++){ 
   // index through all the words in listB
   for(j = 0; j < blineno; j++){ 
      if(strcmp(aline[i], bline[j]) == 0){
        printf("%s is in the list!", bline[j]);
      }
      continue;
      if(strcmp(aline[strlen(aline[0])-1], bline[j]) != 0){
        printf("%s is not in the list!", bline[j]);
      }
   }
 }

Input:输入:

  1. listA: Aardvark,Cat,Bear,Dog清单A:土豚,猫,熊,狗
  2. listB: Cat,Badger listB:猫,獾

Expected Output:预期 Output:

Cat is in the list!猫在名单上! Badger is not in the list!獾不在列表中!

Actual Output:实际 Output:

Cat is in the list!猫在名单上!

EDIT:编辑:

I understand that my continue statement is the reason why the second condition is not being checked.我了解我的continue语句是未检查第二个条件的原因。 Removing it would print a word is / is not in the list 'j' amount of times, which is not my desired output.删除它会打印一个单词 is / is not in list 'j' 的次数,这不是我想要的 output。 In other words, I would appreciate guidance on how I should implement such statements in order to meet the specifications.换句话说,如果我应该如何实施此类声明以满足规范,我将不胜感激。

My suggestion is that you change the loops, so you have the loop over "listB" as the outer loop, and iterate over "listA" in the inner loop.我的建议是更改循环,因此将“listB”上的循环作为外部循环,并在内部循环中迭代“listA”。

Then you can easily set a flag in the inner loop, and break out of it when a match is found.然后您可以轻松break在内部循环中设置一个标志,并在找到匹配项时退出它。 In the outer loop you check this flag to decide what to print.在外部循环中,您检查此标志以确定要打印的内容。

In pseudo code perhaps something like this代码中可能是这样的

for (to_find in listB)
{
    found_flag = false;

    for (animal in listA)
    {
        if (to_find == animal)
        {
            found_flag = true;
            break;
        }
    }

    if (found_flag)
        printf("Animal found");
    else
        printf("Animal not found");
}

Your continue is always executed;你的continue总是被执行; you will never reach your second if .你永远不会达到你的第二个if

First, use goto , like this:首先,使用goto ,如下所示:

void something(void) {
    // index through listA
    for(int i = 0; i < alineno; i++){ 
        // index through all the words in listB
        for(int j = 0; j < blineno; j++){ 
            if(strcmp(aline[i], bline[j]) == 0){
                printf("%s is in the list!", bline[j]);
                goto doneAnimal;
            }
        }
        printf("%s is not in the list!", bline[i]);
doneAnimal: ;
    }
}

Second;第二; to avoid the risk of "goto is bad" nonsense (see Historical Note below), make the code harder to read by splitting it into 2 different functions, so that you can convert the goto into a return , like this:为避免“goto is bad”胡说八道的风险(请参阅下面的历史注释),通过将代码拆分为 2 个不同的函数来使代码更难阅读,这样您就可以将goto转换为return ,如下所示:

void something(void) {
    // index through listA
    for(int i = 0; i < alineno; i++){ 
        doAnimal(i, blineno);
    }
}


void doAnimal(int i, int blineno) {
    for(int j = 0; j < blineno; j++){ 
        if(strcmp(aline[i], bline[j]) == 0){
            printf("%s is in the list!", bline[j]);
            return;
        }
    }
    printf("%s is not in the list!", bline[i]);
}

Historical Note历史记录

Once upon a time higher level languages (like assembly language) did not have structured programming features ( do , while , break , continue , switch , ...).曾几何时,高级语言(如汇编语言)没有结构化的编程功能( dowhilebreakcontinueswitch ……)。 Instead programmers would write code using goto , like (eg) " if(x < MAX) goto loopStart; instead of a " } while(x < MAX);相反,程序员会使用goto编写代码,例如 (eg) " if(x < MAX) goto loopStart;而不是 " } while(x < MAX); . .

To encourage the adoption of structured programming features, in 1968 Edsger W. Dijkstra wrote a letter to the editor of ACM entitled "go to statement considered harmful".为了鼓励采用结构化编程特性,1968 年 Edsger W. Dijkstra 给 ACM 的编辑写了一封题为“go to statement认为有害”的信。 This letter had the desired effect - structured programming features ( do , while , break , continue , switch , ...) were adopted in all major languages.这封信具有预期的效果——结构化编程特性( dowhilebreakcontinueswitch 、...)被所有主要语言采用。

However;然而; it also had one unintended side-effect - the letter was a little too effective;它还有一个意想不到的副作用——这封信有点太有效了; and ignorant people (that failed to read the letter or understand its context) started becoming zealots, making their code worse (for cases where the new structured language features aren't enough) to avoid goto without understanding why, and encouraging other people to make their code worse without understanding why.并且无知的人(没有阅读这封信或理解其上下文)开始成为狂热者,使他们的代码变得更糟(对于新的结构化语言功能还不够的情况),在不了解原因的情况下避免 goto,并鼓励其他人制作他们的代码更糟,不明白为什么。

Examples of this include complicating code by introducing extra variables purely for the sake of avoiding a simpler goto , and/or complicating code to introduce extra branches purely for the sake of avoiding a simpler goto .这方面的示例包括通过引入额外变量来使代码复杂化,纯粹是为了避免更简单的goto ,和/或使代码复杂化以引入额外分支纯粹是为了避免更简单的goto

Later (in conversations with Donald E. Knuth);后来(在与 Donald E. Knuth 的谈话中); Dijkstra himself said " Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. I have the uncomfortable feeling that others are making a religion out of it , as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline! " Dijkstra 自己说:“请不要陷入相信我对 [go 声明] 非常教条主义的陷阱。我有一种不舒服的感觉,其他人正在把它变成一种宗教,好像编程的概念问题可以只需一个技巧,一种简单的编码规则就能解决!

Sadly;可悲的是; once ignorance begins to spread common sense is fighting a losing battle.一旦无知开始传播常识,那就是一场必败之战。

The best way to do this is probably binary search or a hash table, depending on the amount of data.执行此操作的最佳方法可能是二进制搜索或 hash 表,具体取决于数据量。 That being said, the code could be improved in the following way:话虽如此,可以通过以下方式改进代码:

for(int i = 0; i < alineno; i++)
{ 
  int j;
  for(j = 0; j < blineno; j++)
  {
    if(strcmp(aline[i], bline[j]) == 0)
      break;
  }

  if(j == blineno)
    printf("%s is not in the list!", aline[i]); 
  else
    printf("%s is in the list!", bline[j]);
}

Note: aline[i] not bline[i] in the printf.注意:printf 中的 aline[ aline[i]不是bline[i] bline[i] would be a potential array out of bounds bug, if alineno and blineno are allowed to have different lengths.如果允许alinenoblineno具有不同的长度, bline[i]将是一个潜在的数组越界错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM