简体   繁体   中英

This is a c code to find the average in an array of 50 elements using a function

#include <stdio.h>
#include <stdlib.h>
float Findaverage(float n,float numbers[]) {
    float sum = 0;
    for (int j = 0; j < n; j++) {
        sum += numbers[j];
    }
    printf("The average number of the array is: %f", sum/n);

}




int main() {
    int sum = 0;
    float numbers[50];
    float average;
    printf("Enter 50 elements: ");
    // taking input and storing it in an array
    for(int i = 0; i < 50; ++i) {
        scanf("%f", &numbers[i]);
    }
    average = Findaverage(50,numbers[50]);
    printf("\nThe average number of the array is: %f", average );

    return 0;
}

The output gives an error "passing 'float' to parameter of incompatible type 'float *'; take the address with &". Why is this?

For starters the function Findaverage returns nothing.

You need to add this statement to the function

return sum / n;

And the first parameter shall have an integer type instead of the type float .

float Findaverage(float n,float numbers[]) {
                  ^^^^^

Secondly in this call of the function

average = Findaverage(50,numbers[50]);

the argument numbers[50] having the type float instead of the type float * is invalid. You need to write

average = Findaverage(50,numbers);

The function can be declared and defined the following way

double Findaverage( const float numbers[], size_t n ) 
{
    double sum = 0.0;

    for ( size_t i = 0; i < n; i++ ) 
    {
        sum += numbers[i];
    }

    return n == 0 ? 0.0 : sum / n;
}

And the function can be called like

double average = Findaverage( numbers, sizeof( numbers ) / sizeof( *numbers ) );

Change

average = Findaverage(50,numbers[50]);

to

average = Findaverage(50,numbers);

numbers[50] refers to a single array element, not the entire array. It's also one past the end of your array (which is indexed from 0 to 49 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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