【问题标题】:How can i create an if statement within a for loop that breaks the for loop in c?如何在 for 循环中创建一个 if 语句来打破 c 中的 for 循环?
【发布时间】:2021-03-25 21:42:56
【问题描述】:

我正在编写一些 C 代码。我正在尝试创建一个 for 循环,其中包含一个 if 语句。我希望这个 if 语句打破 for 循环。

        for(int i = 0; i != n; i++){
            if(dashes[i] == '-'){
                break;
            }
            stillPlaying = 2;
        } 

基本上,我希望程序检查数组“破​​折号”,如果它找到破折号,它会中断 for 循环并继续执行其余代码。如果它没有找到破折号,则 for 循环被破坏并且 stillPlaying 设置为 2。有没有办法做到这一点?

【问题讨论】:

  • 您是否尝试过您发布的代码?其中的break 语句退出for 循环。
  • 你认为break 在做什么?你有工作代码。你甚至没有尝试运行它吗?
  • 这是什么意思? “如果它没有找到破折号,for 循环被打破”你的意思是你到达数组的末尾并且循环没有通过break 离开?
  • 我尝试了以下代码,但它在我的程序中没有按预期工作,我假设这意味着它因为其他原因而无法工作。谢谢。

标签: arrays c loops if-statement break


【解决方案1】:

重新安排你的方式

    stillPlaying = 2;
    for (int i = 0; i != n; i++) {
        if (dashes[i] == '-') {
            stillPlaying = -1;
            break;
        }
    }
    // stillPlaying is either -1 or 2 here
    // -1 if a '-' was found in dashes

【讨论】:

    【解决方案2】:

    你的意思好像是下面这个

    int i = 0;
    
    while ( i < n && dashes[i] != '-' ) i++;
    
    if ( i == n ) stillPlaying = 2;
    

    【讨论】:

      【解决方案3】:

      我认为代码应该可以正常工作,一旦 - 将出现 break 将发挥作用,并且将退出循环。

      【讨论】:

        【解决方案4】:

        我测试过没有问题。

        #include <stdio.h>
        
        char dashes[10] = {'1', '2', '3', '-', '4'};
        int stillPlaying = 0;
        int n = 5;
        
        int main()
        {
            for(int i = 0; i != n; i++){
                if(dashes[i] == '-')
                    break;
                stillPlaying = 2;
                printf("dashes:%c stillPlaying:%d\n", dashes[i], stillPlaying);
            } 
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-16
          • 2019-06-09
          相关资源
          最近更新 更多