-5

Once the result value is fixed to int, we want to take the mean of these arrays to decimal point, but even if we change it to (float) *result = sum_address/5; in the function call_address, there should be no error.

#include <stdio.h>

void call_value(int A[], int result)
{
        int i;
        int sum = 0;
        for(i = 0; i < 5; i++)
        {
                sum += A[i];
        }

        result = sum / 5;
}

void call_address(int A[], int *result)
{
        int i;
        double sum_address = 0;

        for(i = 0; i < 5; i++)
        {
                sum_address += A[i];
        }

        *result = sum_address / 5;
}

int main()
{
        int result = 0;
        int A[5] = {95, 88, 76, 54, 85};

        call_value(A,result);
        printf("[Call by value] result = %d\n",result);

        call_address(A,&result);
        printf("[Call by address] result = %.1f\n",(float)result);
}

We expected the average of the arrays to be 79.6. But only 79.0. Because this is a task, the int result = 0 and int *result should not change.

Ain
  • 1
  • 3

1 Answers1

0

I'll go out on a limb and guess that you were expected to do the division in main, with the two functions only being used to sum the values of the array.

#include <stdio.h>

void call_value(int A[], int result)
{
    for (int i = 0; i < 5; i++)
    {
        result += A[i];
    }
}

void call_address(int A[], int *result)
{
    for(int i = 0; i < 5; i++)
    {
        *result += A[i];
    }
}

int main(void)
{
    int result = 0;
    int A[5] = { 95, 88, 76, 54, 85 };

    call_value(A, result);
    printf("[Call by value] result(%d) = %.1f\n", result, result / 5.0);

    call_address(A, &result);
    printf("[Call by address] result(%d) = %.1f\n", result, result / 5.0);
}

Output:

[Call by value] result(0) = 0.0
[Call by address] result(398) = 79.6

Otherwise, without being able to change the data type of result, there is not a reasonable solution to this problem.

Oka
  • 23,367
  • 6
  • 42
  • 53