简体   繁体   中英

Finding the average, maximum, minimum value of array in c

I am trying to get the smallest and the largest values of the array. An array which is created by user. I keep getting Segmentation fault (core dumped) . I don't know where I am doing wrong.

#include <stdio.h>
int main(void){
    int n, i;
    double sum = 0.0, array[n], avg;
    printf("Enter the size of the array:");
    scanf("%d", &n);

    for (i=0; i<n; ++i){
        printf("Enter the number for position %d: ", i + 1);
        scanf("%i", &n);
        sum += n;
    }
    avg = (double) sum / n;
    printf("Average = %.2f\n", avg);
        
    double largest = array[0], smallest = array[0];

    for (i = 0; i < n; i++){
        if (array[i] > largest)
        {
            largest = array[i];
        }
        else if (array[i] < smallest)
        {
            smallest = array[i];
        }
    }
    printf("The smallest is %lf and the largest is %lf!\n", smallest, largest);    
}

Edit: After solving this problem, I saw that I also can't get the smallest and largest values. I keeps giving 0.000000 for both. How do I solve it? I tried the change double to float but didn't work..

You wrote array[n] before initialing n . This will invoke undefined behavior for using (indeterminate) value of uninitialized non-static local variable n .

The array allocating must be after reading n . It will be like this:

    int n, i;
    double sum = 0.0, avg;
    printf("Enter the size of the array:");
    scanf("%d", &n);
    double array[n];

@MikeCAT is totally right...

But, if you use c89 or c90 standard you will not able to get the data from the user and then declare the array. and probably get this message when you try to compile it:

ISO C90/C89 forbids mixed declarations and code in C

what you will able to do is to dynamically allocate it, using malloc or calloc.

i see you don't use this standard but i write it anyway so if anyone will see this it could prevent a possible question..

if you do not know which c standard you use check your compilation instructions if there is "-ansi" or "std=c99" flag that means you use the c89 or c90 standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM