简体   繁体   English

在 c 中查找数组的平均值、最大值、最小值

[英]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) .我不断收到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.我一直为两者提供0.000000 How do I solve it?我该如何解决? I tried the change double to float but didn't work..我尝试改变double float但没有工作..

You wrote array[n] before initialing n .您在初始化n之前编写了array[n] This will invoke undefined behavior for using (indeterminate) value of uninitialized non-static local variable n .这将调用未定义的行为来使用未初始化的非静态局部变量n的(不确定的)值。

The array allocating must be after reading n .分配数组必须在读取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... @MikeCAT 完全正确...

But, if you use c89 or c90 standard you will not able to get the data from the user and then declare the array.但是,如果您使用 c89 或 c90 标准,您将无法从用户那里获取数据然后声明数组。 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.您将能够做的是使用 malloc 或 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.如果您不知道您使用的是哪个 c 标准,请检查您的编译说明是否有“-ansi”或“std=c99”标志,这意味着您使用的是 c89 或 c90 标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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