如何将数组传递给函数

时间:2015-12-18 14:43:53

标签: c arrays function

我正在尝试编写一个计算一些行李和重量的程序。我在不使用函数的情况下编写了它,但我必须使用函数,而且我真的很糟糕。

代码通常有效,但我无法用函数实现它。它在打印数组A后停止工作,打印数组B时仅停止0。

我的代码是:

#include <stdio.h>
#include <math.h>
int f1(int N);
int f2(int N);
int f3(int N, float A[20]);

int main(void)
{
    int N;
    f1(N);
    return 0;
}

int f1(int N)
{
    for(;;)
    {
        printf("Enter N(the number of bags) (Between 1 and 20): ");
        scanf("%d", &N);
        if (N < 1 || N > 20)
        {
            continue;
        }
        else
        {
            break;
        }
    }
    f2(N);
}

int f2(int N)
{
    float A[20];
    int i;
    for(i=0; i<N;i++)
    {
        printf("Enter the weight of the bag with potatoes %d: ", i+1);
        scanf("%f", &A[i]);
    }

    printf("\n\nThe weights of the initial bags (the A array):\n");
    for(i=0; i<N;i++)
    {
        printf("%.1f " ,A[i]);
    }
    f3(N, &A[20]);
}

int f3(int N, float A[20])
{
    int i;
    float B[10];
    printf("\n\nNow we equalize the weights of bags.\n");
    if (N%2 == 0)
    {
        for(i=0;i<N/2 ;i++)
        {
            B[i] = fabsf(A[i] - A[N-1-i]);
        }
    }
    else
    {
        for(i=0;i<N/2 ;i++)
        {
            B[i] = fabsf(A[i] - A[N-1-i]);
        }
        B[N/2] = A[N/2];
    }

    if (N%2 == 0)
    {
        for (i=0; i<N/2; i++)
    {
        if (A[i] < A[N-1-i])
        {
            A[N-1-i] = A[i];
        }
        else
        {
            A[i] = A[N-1-i];
        }
    }
    }
    else
    {
        for (i=0; i<N/2; i++)
        {
            if (A[i] < A[N-1-i])
            {
                A[N-1-i] = A[i];
            }
            else
            {
                A[i] = A[N-1-i];
            }
        }
        A[N/2] = 0;
    }

    printf("\nThe weights of the new bags (the B array):\n");
    if (N%2 == 0)
    {
        for(i=0; i<N/2 ;i++)
        {
            printf("%.1f " ,B[i]);
        }
    }
    else
    {
        for(i=0; i<N/2 ;i++)
        {
            printf("%.1f " ,B[i]);
        }
        printf("%.1f", B[N/2]);
    }

    printf("\nThe new weights of the initial bags (the A array):\n");
    for(i=0;i<N;i++)
    {
        printf("%.1f ", A[i]);
    }
}

2 个答案:

答案 0 :(得分:5)

要将数组传递给函数,只需使用其名称。

f3(N, &A[20]);

应该是

f3(N, A);

答案 1 :(得分:2)

要在C中调用函数时传递数组或指针作为参数,您只需要传递它的名称,在您的情况下,

f3(N, A);

此外,在声明函数时,数组的长度无关紧要,因为C不对形式参数执行边界检查。虽然它会以这种方式工作,但最好改变

int f3(int N, float A[20])

int f3(int N, float A[])

int f3(int N, float* A)
相关问题