0

I am programming a method that finds the average, the maximum of 100 numbers that are stored in a vector.

Next, I show the code that I am doing.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int points[100]; 

int main()
{   
    int i;
    int k=sizeof(points)/sizeof(int);
    double points_moy(int[]);
    int points_max(int[]);
    for (i = 0; i < k; i++) {
        points[i] = rand()%121;
        printf("%i-",points[i]); //I show the vector
        }
        printf("\n mean=%f\n", points_moy(points)); // I show the mean  
        printf("\n max=%i \n", points_max(points));// I show the max,
                                                           //here is the 
                                                           //"error"    
        return 0;
}

double points_moy( int points[]) {
    int sum=0, i;
    int m=sizeof(points)/sizeof(int);
    for(i=0; i<m; i++){

        sum=sum+points[i];

    }
    return((float)sum/m);
}

int points_max(int vec[]) {
    int i;
    int max=vec[0];
     int len=sizeof(vec)/sizeof(int);

    for (i = 0; i < len; i++) {
        if (vec[i] > max) {
            max = vec[i];
        }
    }
    return max;
}

Create the method to find the maximum, but at the moment of calling it and compiling the algorithm, it shows me an incorrect value (in most compilations max = 7 but it should be max = 119).

I do not know if the function points_max has any problem, or when calling the function in the main the error is generated.

Alex Pozo
  • 168
  • 7
  • 4
    `sizeof(points)/sizeof(int);` is *not* going to give you what expect when `points` is a pointer (and that's what it is when driven through a function argument list). Fyi the function argument is shadowing the global `points`, which itself is possibly an issue unto itself. – WhozCraig Apr 29 '19 at 17:57
  • 2
    ...you already defined `int points[100];` so you *know* how many elements. You can either pass that `100` as a function argument, or refer to say `#define ELEMENTS 100` and use that throughout. Note that the function argument defined as an "array" actually receives a pointer, and nothing is known about that except its type. A relevant FAQ is [How to find the 'sizeof' (a pointer pointing to an array)?](https://stackoverflow.com/questions/492384/how-to-find-the-sizeof-a-pointer-pointing-to-an-array) – Weather Vane Apr 29 '19 at 18:00

0 Answers0