尝试打印最小值、最大值和平均值。最小值未正确打印

Trying to print smallest, biggest and the mean value. Smallest isn't being printed correctly

因此,我正在尝试创建一个程序来输出最小输入、最大输入以及输入的均值或平均值。到目前为止,最大和平均值都有效,但除非我输入低于 0 的值,否则最小值始终打印为“0.00”,即使最小值高于 0。

#include <stdio.h>
#include <math.h>

int main (void) {

    float input;
    float mean = 0.00;
    float total = 0.00;
    float numOfInput = 0.00;
    float smallest;
    float largest;

    while (scanf ("%f", &input) != EOF && input >= -100000 && input <= 100000) {
        numOfInput++;
        total += input;
        if (input > largest)
            largest = input;
        else if (smallest > input)
            smallest = input;

    }

    mean = (total / numOfInput);
    printf ("%.2f %.2f %.2f\n", smallest, largest, mean);
}

有什么建议吗?我已经坚持了将近一个小时了。正如我之前所说,当我输入一个低于 0 的值时,此方法工作正常,但对于高于 0 的任何值则无效。

非常感谢!

您的代码存在缺陷,因为 1) scanf("%f",&input)!=EOF 不是您检查有效 input 的方式(正如 David C. Rankin 指出的那样);和 2) 你没有初始化 smallestlargest;所以严格来说你的结果可能是不确定的。

我认为您需要将 smallestlargest 号码初始化为第一个有效的 input

float input; 
float mean = 0.00;
float total = 0.00;
unsigned int numOfInput = 0;  // <-- note this is `unsigned int`, not `float`
float smallest = 0; // <-- don't forget this
float largest = 0;  // <-- and this

while( scanf("%f",&input)==1 && input>= -100000 && input <= 100000 )
{
    numOfInput++;
    if( numOfInput == 1 )  // <-- Assign `smallest` and `largest` on first valid input
    {
        smallest = input;
        largest = input;
    }

    total += input; 

    if(input>largest)
        largest = input;
    else if(smallest>input)
        smallest = input;
}

您只能使用 if...else 而不是 if... else if

if(input>largest)
        largest = input;
else 
        smallest = input; 

为什么?因为如果 input 不大于 largest 值,那么它显然是最小的,您可以直接将值存储在 smallest 变量中。
试试这个,你一定会得到正确的答案。