You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C程序中部分if条件满足时未打印错误信息?

飞机飞行时间计算程序的输入验证问题

我编写了一个C程序,用于计算飞机飞行时间并生成对应距离范围的结果表格。需求是先检查用户输入的值能否生成有效表格,若不能则打印错误信息。我用if语句配合printf实现该逻辑,但仅当upper <= 0和upper <= kmlower这两个条件成立时,程序会中断循环却不打印错误信息;而kmlower <= 0、step <= 0条件触发时,错误信息可以正常输出。

我的代码

/* Description: Program to calculate the flight time of an aeroplane,
 *              and tabulate it for a range of values of the distance
 *              travelled.
 *
 *==================================================================*/

/*==================================================================
 * Systems header files
 *==================================================================*/
#include <stdio.h>
#include <math.h>

/*==================================================================
 * Constant definitions
 *==================================================================*/
#define KMTOMILES 0.621371;
#define AVGVELOCITY 529;

/*==================================================================
 * Function definitions
 *==================================================================*/

int main(void)
{
    /* Declaration of variables */
    int FlighttHours, intFlighttMin;
    float kmlower, upper, step /*km = lower */;
    float FlighttRem, miles, totalFlightt, floatFlighttMin;

    /* Interact with the user */
    printf("Enter the lower limit on distance in km:\t  ");
    scanf("%f", &kmlower);

    printf("Enter the upper limit on distance in km:\t  ");
    scanf("%f", &upper);

    printf("Enter the step size in km:\t\t\t  ");
    scanf("%f", &step);


    while (kmlower <= upper) /* Create output table */
    {
        /* Check if the values input by the user will produce a valid table */
        if ((kmlower <= 0) || (upper <= 0) || (step <= 0) || (upper <= kmlower))
        {
            printf("\nERROR: these values will not produce a valid output table\n");
            break;
        }

        /* Continue loop if no errors */
        else
        {
            /* Print table headers once */
            printf("\n=================================================\n");
            printf("| distance (km) |     hours     |     minutes   |\n");
            printf("|===============================================|\n");

            /* Loop until upper limit is reached */
            while (kmlower <= upper)
            {
                /* Print range of distances */
                printf("|%10.2f\t|", kmlower);

                /* Calculate journey times */
                miles = kmlower * KMTOMILES;
                totalFlightt = miles / AVGVELOCITY;
                FlighttHours = (int)(totalFlightt);
                FlighttRem = totalFlightt - FlighttHours;
                floatFlighttMin = FlighttRem * 60;
                intFlighttMin = round(floatFlighttMin);

                /* Print results */
                printf("\t%d\t|\t%d\t|\n", FlighttHours, intFlighttMin );
                kmlower += step;
            }
        }
    }

    return (0);
}

运行结果示例

情况1:kmlower <= 0(错误信息正常打印)

Enter the lower limit on distance in km:         0
Enter the upper limit on distance in km:         4000
Enter the step size in km:                       500

ERROR: these values will not produce a valid output table

Process returned 0 (0x0)   execution time: 3.977 s
Press any key to continue.

情况2:step <= 0(错误信息正常打印)

Enter the lower limit on distance in km:         500
Enter the upper limit on distance in km:         4000
Enter the step size in km:                       0

ERROR: these values will not produce a valid output table

Process returned 0 (0x0)   execution time: 7.016 s
Press any key to continue.

情况3:upper <= 0(无错误信息)

Enter the lower limit on distance in km:         500
Enter the upper limit on distance in km:         0
Enter the step size in km:                       200

Process returned 0 (0x0)   execution time: 14.927 s
Press any key to continue.

情况4:upper <= kmlower(无错误信息)

Enter the lower limit on distance in km:         500
Enter the upper limit on distance in km:         400
Enter the step size in km:                       200

Process returned 0 (0x0)   execution time: 7.084 s
Press any key to continue.

问题原因

核心问题出在最外层的while (kmlower <= upper)循环:

  • 当upper <= 0或upper <= kmlower时,循环条件直接不成立,程序根本不会进入循环体,自然不会执行里面的错误判断和打印逻辑。
  • 而kmlower <=0或step <=0时,kmlower <= upper的条件是成立的(比如kmlower=0、upper=4000),所以能进入循环触发错误提示。

修复方案

把输入验证逻辑移到最外层循环之前,先完成所有输入的有效性检查,不通过直接打印错误;验证通过后再进入表格生成的循环。

修改后的代码:

/* Description: Program to calculate the flight time of an aeroplane,
 *              and tabulate it for a range of values of the distance
 *              travelled.
 *
 *==================================================================*/

/*==================================================================
 * Systems header files
 *==================================================================*/
#include <stdio.h>
#include <math.h>

/*==================================================================
 * Constant definitions
 *==================================================================*/
#define KMTOMILES 0.621371;
#define AVGVELOCITY 529;

/*==================================================================
 * Function definitions
 *==================================================================*/

int main(void)
{
    /* Declaration of variables */
    int FlighttHours, intFlighttMin;
    float kmlower, upper, step, current_km;
    float FlighttRem, miles, totalFlightt, floatFlighttMin;

    /* Interact with the user */
    printf("Enter the lower limit on distance in km:\t  ");
    scanf("%f", &kmlower);

    printf("Enter the upper limit on distance in km:\t  ");
    scanf("%f", &upper);

    printf("Enter the step size in km:\t\t\t  ");
    scanf("%f", &step);

    /* 先做输入验证 */
    if ((kmlower <= 0) || (upper <= 0) || (step <= 0) || (upper <= kmlower))
    {
        printf("\nERROR: these values will not produce a valid output table\n");
        return 0; // 直接退出程序
    }

    /* 验证通过,生成表格 */
    printf("\n=================================================\n");
    printf("| distance (km) |     hours     |     minutes   |\n");
    printf("|===============================================|\n");

    current_km = kmlower; // 用临时变量保存初始值,避免修改原输入变量
    while (current_km <= upper)
    {
        /* Print range of distances */
        printf("|%10.2f\t|", current_km);

        /* Calculate journey times */
        miles = current_km * KMTOMILES;
        totalFlightt = miles / AVGVELOCITY;
        FlighttHours = (int)(totalFlightt);
        FlighttRem = totalFlightt - FlighttHours;
        floatFlighttMin = FlighttRem * 60;
        intFlighttMin = round(floatFlighttMin);

        /* Print results */
        printf("\t%d\t|\t%d\t|\n", FlighttHours, intFlighttMin );
        current_km += step;
    }

    return (0);
}

修改说明:

  1. 将输入验证逻辑移到循环外,确保所有无效输入都能被检测到并打印错误。
  2. 使用临时变量current_km遍历距离范围,避免修改原始的kmlower变量(原代码中修改kmlower会导致后续逻辑混乱)。
  3. 验证不通过时直接return 0退出程序,无需进入循环。

内容的提问来源于stack exchange,提问作者Bon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 16:54:55