找到数组的中位数

时间:2016-05-29 10:47:51

标签: c

#include<stdio.h>
#include<stdlib.h>
double median(int n, int arr[])
{
    int i, j, a;
    for (i = 0; i < n; ++i)
    {
        for (j = i + 1; j < n; ++j)
        {
            if (arr[i] > arr[j])
            {
                a = arr[i];
                arr[i] = arr[j];
                arr[j] = a;
            }
            if (arr[i] > arr[j])
            {
                a = arr[i];
                arr[i] = arr[j];
                arr[j] = a;
            }
        }
    }
    if (n % 2 == 0) 
    {
        return((arr[n / 2] + arr[n / 2 - 1]) / 2.0);
    }
    else {
        return arr[n / 2];
    }
    for (i = 0; i < n; i++)
    {
        printf("%d\n", arr[i+1]);
    }
}
int main()
{
    int arr[100] = { 0 };
    int i, n, sum = 0;
    printf("How many numbers would you like to enter?");
    scanf_s("%d", &n);
    while (n > 100 || n < 0)
    {
        printf("Amount of numbers should be less than 0 and more than 100\n");
        scanf_s("%d", &n);
    }
    for (i = 0; i < n; i++)
    {
        scanf_s("%d", &arr[i + 1]);
    }
    printf("%f", median(n, arr));
    system("pause");
}

好像我的函数不会得到中值函数。该函数对数组排序很好,但找到中位数是个问题。只要函数找到中位数,它就会输出另一个值。任何类型的帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我已经修改了一下你的代码,现在工作正常。您不需要if函数的内部for循环中的第二个median条件。我还删除了system("pause")命令并在main函数中正确设置了数组索引(将arr[i+1]更改为arr[i])。我也删除了

while (n > 100 || n < 0)
    {
        printf("Amount of numbers should be less than 0 and more than 100\n");
        scanf_s("%d", &n);
    }

并将scanf_s更改为scanf。

修改后的代码:

#include<stdio.h>
#include<stdlib.h>
double median(int n, int arr[])
{
    int i, j, a;
    for (i = 0; i < n; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (arr[i] > arr[j])
            {
                a = arr[i];
                arr[i] = arr[j];
                arr[j] = a;
            }

        }
    }

    for (i = 0; i < n; i++)
    {
        printf("%d\n", arr[i]);
    }
    if (n % 2 == 0) 
    {
        return((arr[n / 2] + arr[n / 2 - 1]) / 2.0);
    }
    else {
        return arr[n / 2];
    }

}
int main()
{
    int arr[100] = { 0 };
    int i, n;
    printf("How many numbers would you like to enter?");
    scanf("%d", &n);

    for (i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }
    printf("%f", median(n, arr));

return 0;
}