虽然使用EOF循环让我感到困惑

时间:2018-06-12 15:19:32

标签: c

我对学习C很新,很抱歉,如果这个问题非常简单。这是我正在尝试编写的程序 - 其目的是在达到EOF之前获取输入,然后输出所有输入值的最大值和最小值。

编译和运行后的问题是这样的:输入值后我按下EOF快捷键CTRL + Z然后按下此快捷键后,不会打印代码末尾写的值(最小值和最大值)。所以我很困惑 - 因为我编写了代码,以便在达到EOF时输出最大值和最小值。

#include <stdio.h>

int main(void) {
    // declare variables
    float input = 0;
    float max = 0;
    float min = 0;

    // take input and make it equal to return value
    int return_value = scanf("%f", &input);

    // while return_value does not equal EOF
    while (return_value != EOF) {
        // if input is larger than the max
        if (input > max) {
            // then the input becomes the max
            input = max;
        }
        // else if the input is less than the min
        else if (input < min) {
            // than the input becomes the min
            input = min;
        }

        int return_value = scanf("%f", &input);
    }

    // print the largest number
    printf("%.2f ", max);

    // print the smallest number
    printf("%.2f\n", min);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

正如其他人指出的...... 您正在重新定义return_value

尽管如此...... 我不认为使用EOF是可靠的。如果您愿意考虑替代方案,可以尝试以下方法 - 当用户键入任何非数字字符时会中断循环。

#include <stdio.h>

int main(void) {
    // declare variables
    float input = 0;
    float max = 0;
    float min = 0;

    // take input and make it equal to return value
    int n_convs = scanf("%f", &input);

    // while return_value does not equal EOF
    while (n_convs > 0) {
        // if input is larger than the max
        if (input > max) {
            // then the input becomes the max
            max = input;
        }
        // else if the input is less than the min
        else if (input < min) {
            // than the input becomes the min
            min = input;
        }

        n_convs = scanf("%f", &input);
    }

    // print the largest number
    printf("%.2f ", max);

    // print the smallest number
    printf("%.2f\n", min);

    return 0;
}

另请注意,循环中的逻辑有些错误...... 它必须是

if (input > max) {
    // then the input becomes the max
    max = input;
}

(不是input = max)。