The code does not work in the terminal

I just started learning C, and before that I don't know programming.

So, I'm trying to run this one stat program, which will read the input and give you the average, variance, etc. I used the terminal to run the program. I pretty much copied the code from the book I'm using.

There were no errors when running the code, but when I entered the input, it did nothing. The code is below.

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

int main()
{
    float x, max, min, sum, mean, sum_of_squares, variance;
    int count;
    printf("Enter data: "); /* not included in the original code*/

    if( scanf("%f", &x) == EOF )
        printf("0 data items read.\n");
    else{
        max = min = sum = x;
        count = 1;
        sum_of_squares = x * x;
        while(scanf("%f", &x) != EOF) {
            count += 1;
            if (x > max)
                max = x;
            if ( x < min)
                min = x;
            sum += x;
            sum_of_squares += x * x;
        }
        printf("%d data items read\n", count);
        printf("maximum value read = %f\n", max);
        printf("minimum value read = %f\n", min);
        printf("sum of all values read = %f\n", sum);
        mean = sum/count;
        printf("mean = %f\n", mean);
        variance = sum_of_squares / count - mean * mean;
        printf("variance = %f\n", variance);
        printf("standard deviation = %f\n", sqrt(variance));
    }
}
+4
source share
1 answer

The code is in order as it is. You probably don't understand the termination condition. The program reads the input in an infinite loop, and you need to send EOFto complete the loop.

EOF, ctrl + D unix ctrl + Z .

+11

Source: https://habr.com/ru/post/1623997/


All Articles