首页 > 解决方案 > 在 for 循环中中断 if 语句

问题描述

如何在加仑 < 100 和小时 < 24 的情况下在执行后结束循环显示。我能够得到“鱼在……小时后死去”但不确定如何停止 for 循环中的第一个 printf()执行。

我尝试过在 if 语句中使用缩进的 break 语句,但这只会影响 for 循环。

#include <stdio.h>

int main()
{
    double add, vol = 500;
    int hour;

    printf("Please enter additional water added per hour: ");
    scanf("%lf", &add);

    for (hour = 1; hour <= 24; hour++)
    {

        vol = (vol * 0.90) + add;

        printf("The volume is %.2f gallons after %d hours.\n", vol, hour);

        if (hour <= 23 && vol < 100)
            printf("The fish died after %d hours.", hour);


        else if (hour == 24 && vol >= 100)
            printf("Alas, The fish who lived.");
    }

    return 0;
}

预期结果:

Please enter additional water added per hour: 6
The volume is 456.00 gallons after 1 hours.
The volume is 416.40 gallons after 2 hours.
The volume is 380.76 gallons after 3 hours.
...
The volume is 103.33 gallons after 22 hours.
The volume is 99.00 gallons after 23 hours.
The fish died after 23 hours.

实际结果:

Please enter additional water added per hour: 6
The volume is 456.00 gallons after 1 hours.
The volume is 416.40 gallons after 2 hours.
The volume is 380.76 gallons after 3 hours.
...
The volume is 103.33 gallons after 22 hours.
The volume is 99.00 gallons after 23 hours.
The fish died after 23 hours. The volume is 95.10 gallons after 24 hours.

标签: cfor-loopbreak

解决方案


C 不是 Python,缩进在语法上并不重要。复合语句必须包含在{..}

    if (hour <= 23 && vol < 100)
    {
        printf("The fish died after %d hours.", hour);
        break ;
    }
    else if (hour == 24 && vol >= 100)
    {
        printf("Alas, The fish who lived.");
    }

我建议您始终使用{..}条件块或循环块,即使是单个语句。它使维护更简单。

但是,break;可以说是退出循环的一种相当不雅且结构不佳的方式(与 一起continue)。更好的结构化解决方案是仅通过循环约束来终止循环。在这种情况下,可以通过以下方式完成:

for( hour = 1; 
     vol > 100 && hour <= 24; 
     hour++)

有额外测试的开销,但在比这更复杂的代码中,可能有多个breaks,它可能变得难以维护、调试和理解。


推荐阅读