【问题标题】:Finding the average, maximum, minimum value of array in c在c中查找数组的平均值,最大值,最小值
【发布时间】:2021-06-18 08:51:33
【问题描述】:

我正在尝试获取数组的最小值和最大值。由用户创建的数组。我不断收到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,但没有成功..

【问题讨论】:

    标签: c segmentation-fault average coredump


    【解决方案1】:

    您在初始化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];
    

    【讨论】:

      【解决方案2】:

      @MikeCAT 完全正确...

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

      ISO C90/C89 forbids mixed declarations and code in C
      

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

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

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

      【讨论】:

        猜你喜欢
        • 2014-06-11
        • 2016-01-05
        • 2012-09-27
        • 1970-01-01
        • 1970-01-01
        • 2020-06-17
        • 2018-09-04
        • 1970-01-01
        • 2021-01-15
        相关资源
        最近更新 更多