繁体   English   中英

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

[英]Finding the average, maximum, minimum value of array in c

我正在尝试获取数组的最小值和最大值。 由用户创建的数组。 我不断收到Segmentation fault (core dumped) 我不知道我在哪里做错了。

#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);    
}

编辑:解决这个问题后,我看到我也无法获得最小值和最大值。 我一直为两者提供0.000000 我该如何解决? 我尝试改变double float但没有工作..

您在初始化n之前编写了array[n] 这将调用未定义的行为来使用未初始化的非静态局部变量n的(不确定的)值。

分配数组必须在读取n之后。 它会是这样的:

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

@MikeCAT 完全正确...

但是,如果您使用 c89 或 c90 标准,您将无法从用户那里获取数据然后声明数组。 当您尝试编译它时可能会收到此消息:

ISO C90/C89 forbids mixed declarations and code in C

您将能够做的是使用 malloc 或 calloc 动态分配它。

我看到你没有使用这个标准,但我还是写了它,所以如果有人会看到这个,它可能会阻止一个可能的问题..

如果您不知道您使用的是哪个 c 标准,请检查您的编译说明是否有“-ansi”或“std=c99”标志,这意味着您使用的是 c89 或 c90 标准。

暂无
暂无

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

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