为什么我的 c 程序在我的 if 语句中的条件为 true 后不打印我的错误消息?

Why does my c program not print my error message after a condition is true in my if statement?

提问人:Bon 提问时间:9/30/2023 最后编辑:chqrlieBon 更新时间:9/30/2023 访问量:97

问:

在我的程序中,我想检查用户输入的值是否会生成有效的表格,如果不是,我想打印错误消息。

我用了一个语句,后面跟着 .这适用于我的语句中除 和 条件之外的所有条件。当这些条件为真时,循环将中断,但不会打印错误消息。ifprintfif(upper <= 0)(upper <= kmlower)

这是我的代码:

/* 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);
}

当我运行代码和用户输入 or 时,会打印我的错误消息。kmlower <= 0step <= 0

结果 当 时,并显示错误消息: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.

结果 当 时,并显示错误消息: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.

但是,当用户输入 或 时,代码会像我想要的那样停止,但不会打印错误消息。upper <= 0upper <= kmlower

结果时,无错误消息: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.

结果时,无错误消息: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.
c if 条件语句 printf 条件运算符

评论

2赞 Some programmer dude 9/30/2023
请不要发布文字图片。将所有文本作为文本复制粘贴到您的问题中。
2赞 Some programmer dude 9/30/2023
至于您的问题,请使用调试器逐行单步执行代码,同时监视变量及其值。
2赞 Some programmer dude 9/30/2023
另一方面,除非您有非常具体的要求,否则请不要将浮点值和变量用于浮点值和变量。请改用。floatdouble
0赞 chqrlie 9/30/2023
@chux-ReinstateMonica:恕我直言,执行示例的快照并不像代码图片那样大。我没有添加图片,我只是让图片可见,而不是图片链接。
0赞 chux - Reinstate Monica 9/30/2023
@chqrlie对不起。但要小心你惹了吗? 😉

答:

2赞 B. Pantalone 9/30/2023 #1

您的循环条件是阻止在使用这些输入时进入循环。如果要查看错误消息,请删除外部循环。while (kmlower <= upper)

3赞 chux - Reinstate Monica 9/30/2023 #2

问题:

  • 键:循环条件,同时阻止进入。@B. 潘塔隆(kmlower <= upper)

  • 无法编译,并启用了许多警告。节省时间并启用许多(如果不是全部)警告。

  • 避免混合和数学。在这种情况下,请使用变量而不是 。@Some程序员家伙floatdoubledoublefloat

  • 时间计算不佳:

当 时,代码将输出 “123:60” 而不是 “124:00”。totalFlightt = 123.996

| distance (km) |     hours     |     minutes   |
|===============================================|
|      0.00     |     123       |   60          |

将整个时间四舍五入到最接近的分钟,然后将其分解为小时/分钟的替代代码。

long totalFlightt_minutes = lround(60.0 * miles / AVGVELOCITY);
printf("\t%ld\t|\t%02ld\t|\n", 
   totalFlightt_minutes / 60, totalFlightt_minutes % 60);

只为迂腐的人

  • 转换常量

OP 距离最好的 5 秒。#define KMTOMILES 0.621371floatfloat0.621371210f

不要使用粗常数,而应至少使用以下类型的精度:9 表示 , 17 表示 。floatdouble

更好的是,由于 KM 到 mph 是一个精确的分数,让编译器弄清楚

#define KMTOMILES_ALT (10000000.0f/(5280L*12*254))
  • 正确的单位?

航空很少使用miles_per_hour,而是使用

考虑:

#define KMTOKNOTS (1000.0/1852)
2赞 chqrlie 9/30/2023 #3

输入值的有效性测试在循环主体内执行。对于最后 2 种情况,此初始测试为 false,这解释了为什么您没有获得输出。请注意,此循环是无用的,应将其删除。while (kmlower <= upper)while

另请注意,和 的定义不正确:您应该删除宏定义中的尾随,这将阻止在大多数表达式中使用,除非宏出现在末尾并且尾随只是创建一个额外的空语句。请改用以下方法:KMTOMILESAVGVELOCITY;;

#define KMTOMILES 0.621371
#define AVGVELOCITY 529