Files
  • main.c
  • AllNeg.txt
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
For input: 'AllNeg.txt':
output does not match for me :
Correct output for AllNeg.txt
************************
# items: 11
Sum:     -10999945.000000
Maximum: -999990.000000
Minimum: -1000000.000000
Mean:    -999995.000000
************************

Output for me
************************
# items: 11
Sum: -10999945.000000
Maximum: 0.000000
Minimum: -1000000.000000
Mean: -999995.000000
************************
*/

#include <stdio.h>
#include <float.h>

#define BUFSIZE 256

        int main()
        {
        int     itemsread = 0;
        double  item = -1;     // initial value so loop starts
        int     howmany = 0;
        char    line[BUFSIZE]; // fgets() knows about the NULL

        //create variables for running stats
        double  minimum = DBL_MAX;
        double  maximum = -DBL_MIN;
        double  sum = 0;
        double  average = 0;

        // check last item wasn't zero; if not
        // read the line from input and copy it to memory as a string
        while (item != 0 && fgets(line, BUFSIZE, stdin) != NULL)
        {
                // scan the number from the line - extra stuff on line is ignored
                itemsread = sscanf(line, "%lf", &item);

                // check to see if we got valid input
                if (itemsread == 1 && item != 0)
                {
                        howmany++;  // increase count
                        if (item < minimum)
                                // new min
                                minimum = item;

                        if (item > maximum)
                                // new max
                                maximum = item;

                        sum += item;
                        average = sum / howmany;
                }
                // this will not get stuck in an infinite loop,
                // plus we can examine the input data
                if (itemsread == 0)
                        printf("bad input\n");
        }

        // if we never read anything, dont print stats
        if(howmany == 0)
                printf("# items: %d\n");
        else
                printf("# items: %d\nSum: %f\nMaximum: %f\nMinimum: %f\nMean: %f\n", howmany, sum, maximum, minimum, average);

        return 0;
}