C语言 中断循环,如果循环中断,则不运行下一代码

x9ybnkn6  于 2023-01-12  发布在  其他
关注(0)|答案(5)|浏览(170)
#include <stdio.h>

int main() {
    while (height > 0) {
        if (throttle >= 0 && throttle <= 100) {
            printf("%d    %.1f  %.1f   %.1f  ", time, height, velocity, fuel);
            scanf("%d", &throttle);
            height = heightTemp + velocityTemp - (throttle * K-G) / 2;
            velocity = velocityTemp + (throttle * K-G);
            fuel = fuelTemp - throttle;
            time = time + 1;
            heightTemp = height;
            velocityTemp = velocity;
            fuelTemp = fuel;   
        }
        else {
            printf("Please choose a number between 0 and 100! \n");
            break;
        }
    }
   
    if (velocity >= -2.0) {
        printf("You landed successfully: ");
    } 
    else {
        printf("Failed! You crashed");
    }

    return 0;
}

我只想在循环没有中断的情况下运行if velocity部分,如果我保持代码这样,它会运行代码,无论发生什么,因为中断显然只是退出循环,我没有写完整的代码。

wlsrxk51

wlsrxk511#

基本上有两种解决方案:
1.使用break时设置为1的idBreak变量,如mikyll98's answer中所示
1.使用goto pastTheIfElse;代替break;
如果pastTheIfElse标签标记了return(就像它在代码中所做的那样),那么您可以直接使用return而不是goto

#include <stdio.h>

int main() {
    while (height > 0) {
        if (throttle >= 0 && throttle <= 100) {
            printf("%d    %.1f  %.1f   %.1f  ", time, height, velocity, fuel);
            scanf("%d", &throttle);
            height = heightTemp + velocityTemp - (throttle * K-G) / 2;
            velocity = velocityTemp + (throttle * K-G);
            fuel = fuelTemp - throttle;
            time = time + 1;
            heightTemp = height;
            velocityTemp = velocity;
            fuelTemp = fuel;   
        }
        else {
            printf("Please choose a number between 0 and 100! \n");
            goto pastTheIfElse; //instead of break;
            //OR in this case: `return 0;`
        }
    }

    if (velocity >= -2.0) {
        printf("You landed successfully: ");
    } else {
        printf("Failed! You crashed");
    }
    pastTheIfElse:

    return 0;
}

goto解决方案是一个优化编译器应该优化didBreak版本的东西,所以有些人喜欢它,而另一些人则非常非常强烈地反对它,因为“goto被认为是有害的”。

qlfbtfca

qlfbtfca2#

break;替换为return 0;,或者如果您认为无效,则向主机环境输入错误值return -1;(或其他非零值-它是实现定义的)。
如果你想成为超正式的#include <stdlib.h>return EXIT_SUCCESSreturn EXIT_FAILURE,尽管在真实的代码的例子中很少看到这些宏常量的使用。
一些C标准认为函数应该只有一个出口点,但遵守这一点有时会导致代码像早期返回一样扭曲和不可读。

zbq4xfa0

zbq4xfa03#

只要在循环中断时给变量赋值,并添加一个if条件来检查该值。

#include <stdio.h>

int main() {
    int didBreak = 0;

    while (height > 0)
    {
        if (throttle >= 0 && throttle <= 100)
        {
            printf("%d    %.1f  %.1f   %.1f  ", time, height, velocity, fuel);
            scanf("%d", &throttle);
            height = heightTemp + velocityTemp - (throttle * K - G) / 2;
            velocity = velocityTemp + (throttle * K - G);
            fuel = fuelTemp - throttle;
            time = time + 1;
            heightTemp = height;
            velocityTemp = velocity;
            fuelTemp = fuel;

        }
        else
        {
            printf("Please choose a number between 0 and 100! \n");
            didBreak = 1;
            break;
        }
    }

    if (didBreak == 0)
    {
        if (velocity >= -2.0)
        {
            printf("You landed successfully: ");
        }
        else
        {
            printf("Failed! You crashed");
        }
    }

    return 0;
}
deyfvvtc

deyfvvtc4#

在我看来,解决你所提到的问题的最好方法是用return 1;替换break,这样它就退出了函数,如果你用#include <stdlib.h>,那么你也可以用return EXIT_FAILURE;来代替,这样更容易阅读。
然而,如果你不想退出函数(例如,因为你想执行函数的其余部分),那么我建议你用明确的break语句将循环重构为一个无限循环,这样,你可以在循环中移动if ... else

for (;;) //infinite loop, equivalent to while(true)
{
    if ( height <= 0 )
    {
        if ( velocity >= -2.0 )
        {
            printf( "You landed successfully.\n" );
        }
        else
        {
            printf( "Failed! You crashed!\n" );
        }

        break;
    }

    if ( throttle >= 0 && throttle <= 100 )
    {
        [...]
    }
    else
    {
        printf( "Please choose a number between 0 and 100!\n" );
        break;
    }
}

但是,我不认为你所说的问题是你的实际问题,当用户输入无效的输入时,你可能不想退出功能(或甚至整个程序)。相反,当输入无效时,重新提示用户输入有效将更有意义。为了确定输入是否无效,你不仅要检查throttle是否在所需的范围内,还要检查用户是否在第一个地方输入了整数(即,确保用户没有输入无法转换为整数的内容)。
由于this answer of mine to another question中所述的原因,我不建议您使用scanf进行基于行的用户输入。为了确定用户输入的整数是否有效,通常最好使用函数fgets将用户输入的一行内容读取为字符串。然后尝试使用函数strtol将字符串转换为整数。这两个函数调用可以组合成单个函数,如果用户没有输入有效的整数,它会自动重新提示用户。在我的链接答案中,我创建了一个名为get_int_from_user的函数。
进行上述更改后,您的代码将如下所示:

for (;;) //infinite loop, equivalent to while(true)
{
    printf( "T: %d   H: %.1f   V: %.1f   F: %.1f\n", time, height, velocity, fuel );

    if ( height <= 0 )
    {
        if ( velocity >= -2.0 )
        {
            printf( "You landed successfully.\n" );
        }
        else
        {
            printf( "Failed! You crashed!\n" );
        }

        break;
    }

    //repeat until user entered a valid integer in the
    //range 0 - 100
    for (;;)
    {
        throttle = get_int_from_user( "Enter throttle (0-100): " );
        if ( throttle < 0 || throttle > 100 )
        {
            printf( "Please choose a number between 0 and 100!\n" );
            continue;
        }

        //input is ok
        break;
    }

    //do physics calculations (copied from the question)
    height = heightTemp + velocityTemp - (throttle * K-G) / 2;
    velocity = velocityTemp + (throttle * K-G);
    fuel = fuelTemp - throttle;
    time = time + 1;
    heightTemp = height;
    velocityTemp = velocity;
    fuelTemp = fuel;  
}

下面是一个测试程序的完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>

int get_int_from_user( const char *prompt );

int main( void )
{
    int time = 0, throttle;
    double height = 100.0, velocity = -5.0;

    for (;;) //infinite loop, equivalent to while(true)
    {
        printf( "T: %d   H: %.1f   V: %.1f\n", time, height, velocity );

        if ( height <= 0 )
        {
            if ( velocity >= -2.0 )
            {
                printf( "You landed successfully.\n" );
            }
            else
            {
                printf( "Failed! You crashed!\n" );
            }

            break;
        }

        //repeat until user entered a valid integer in the
        //range 0 - 100
        for (;;)
        {
            throttle = get_int_from_user( "Enter throttle (0-100): " );
            if ( throttle < 0 || throttle > 100 )
            {
                printf( "Please choose a number between 0 and 100!\n" );
                continue;
            }

            //input is ok
            break;
        }

        //do physics calculations
        velocity += throttle / 100.0;
        velocity -= 0.5; //gravity
        height += velocity;
        time++;
    }
}

int get_int_from_user( const char *prompt )
{
    //loop forever until user enters a valid number
    for (;;)
    {
        char buffer[1024], *p;
        long l;

        //prompt user for input
        fputs( prompt, stdout );

        //get one line of input from input stream
        if ( fgets( buffer, sizeof buffer, stdin ) == NULL )
        {
            fprintf( stderr, "Unrecoverable input error!\n" );
            exit( EXIT_FAILURE );
        }

        //make sure that entire line was read in (i.e. that
        //the buffer was not too small)
        if ( strchr( buffer, '\n' ) == NULL && !feof( stdin ) )
        {
            int c;

            printf( "Line input was too long!\n" );

            //discard remainder of line
            do
            {
                c = getchar();

                if ( c == EOF )
                {
                    fprintf( stderr, "Unrecoverable error reading from input!\n" );
                    exit( EXIT_FAILURE );
                }

            } while ( c != '\n' );

            continue;
        }

        //attempt to convert string to number
        errno = 0;
        l = strtol( buffer, &p, 10 );
        if ( p == buffer )
        {
            printf( "Error converting string to number!\n" );
            continue;
        }

        //make sure that number is representable as an "int"
        if ( errno == ERANGE || l < INT_MIN || l > INT_MAX )
        {
            printf( "Number out of range error!\n" );
            continue;
        }

        //make sure that remainder of line contains only whitespace,
        //so that input such as "6sdfj23jlj" gets rejected
        for ( ; *p != '\0'; p++ )
        {
            if ( !isspace( (unsigned char)*p ) )
            {
                printf( "Unexpected input encountered!\n" );

                //cannot use `continue` here, because that would go to
                //the next iteration of the innermost loop, but we
                //want to go to the next iteration of the outer loop
                goto continue_outer_loop;
            }
        }

        return l;

    continue_outer_loop:
        continue;
    }
}

由于你发布的物理计算没有编译,我已经添加了我自己的(简单)物理计算。
此程序具有以下输出:

T: 0   H: 100.0   V: -5.0
Enter throttle (0-100): hh7
Error converting string to number!
Enter throttle (0-100): test
Error converting string to number!
Enter throttle (0-100): 6abc
Unexpected input encountered!
Enter throttle (0-100): 200
Please choose a number between 0 and 100!
Enter throttle (0-100): -30
Please choose a number between 0 and 100!
Enter throttle (0-100): 5 
T: 1   H: 94.5   V: -5.5
Enter throttle (0-100): 10
T: 2   H: 88.7   V: -5.9
Enter throttle (0-100): 15
T: 3   H: 82.5   V: -6.2
Enter throttle (0-100): 20
T: 4   H: 76.0   V: -6.5
Enter throttle (0-100): 25
T: 5   H: 69.2   V: -6.8
Enter throttle (0-100): 35
T: 6   H: 62.4   V: -6.9
Enter throttle (0-100): 45
T: 7   H: 55.4   V: -7.0
Enter throttle (0-100): 55
T: 8   H: 48.5   V: -6.9
Enter throttle (0-100): 65
T: 9   H: 41.8   V: -6.8
Enter throttle (0-100): 80
T: 10   H: 35.3   V: -6.5
Enter throttle (0-100): 100
T: 11   H: 29.3   V: -6.0
Enter throttle (0-100): 100
T: 12   H: 23.9   V: -5.5
Enter throttle (0-100): 100
T: 13   H: 18.9   V: -5.0
Enter throttle (0-100): 100
T: 14   H: 14.5   V: -4.5
Enter throttle (0-100): 100
T: 15   H: 10.6   V: -4.0
Enter throttle (0-100): 100
T: 16   H: 7.1   V: -3.5
Enter throttle (0-100): 100
T: 17   H: 4.2   V: -3.0
Enter throttle (0-100): 100
T: 18   H: 1.7   V: -2.5
Enter throttle (0-100): 100
T: 19   H: -0.2   V: -2.0
You landed successfully.
gcxthw6b

gcxthw6b5#

提示重新输入数据,然后退出处理,去别的地方,这是没有意义的......
修改while循环并在输入时测试用户输入。
可能是“哨兵值”(例如:999)可以用来中止循环...

while( height > 0 ) {
    printf("%d    %.1f  %.1f   %.1f  ", time, height, velocity, fuel);
    scanf("%d", &throttle);
    if( throttle < 0 || throttle > 100 ) {
        if( throttle == 999 ) return -1; // Maybe???
        printf("Please choose a number between 0 and 100! (999 to abort) \n");
        continue;
    }

    /* Calculations omitted */
}

相关问题