1

I'm new to C and I'm trying to master the basics so I've written a program which gives you the mean of tree numbers and it works, but when I try to write a more general version of it, as output I receive: Insert a series of numbers: "The mean of the numbers is -nan". Which means that I can not even insert the numbers. I don't now how to write the scanf part in a better way.

Here's the code:

#include <stdio.h>

int main() {

    int p;
    double n[p];
    int i;
    double sum = 0;
    double m;

    printf("Insert a series of numbers:\n");

    for(int r = 0; r < p; r++) {
        scanf("%lf", &n[r]);
    }

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

    m = sum / p;
    printf("The mean of the numbers is %lf", m);

    return 0;
}
Schiele
  • 125
  • 6
  • 4
    Undefined behaviour. `p` is uninitialized, so defining `double n[p];` is undefined. – P.P Apr 18 '20 at 16:43
  • 1
    There are a few issues here. To start with you haven't defined `p`! How does the `for` loop know when to stop? When you declare variable `int p` it has a random value. Make sure you initialise your variables like `int p=10'` – Rohan Apr 18 '20 at 16:45
  • Can I even make the user decide the value of p? Maybe by putting another printf and scanf before the first for – Schiele Apr 18 '20 at 16:47
  • @Schiele Yes, then is `n` what is called a VLA or variable length array -> https://en.wikipedia.org/wiki/Variable-length_array. – RobertS supports Monica Cellio Apr 18 '20 at 17:06

1 Answers1

3
int p;

You forgot to initialize p. Since p is an object of the automatic storage class, it has an indeterminate value.

Thus,

double n[p];
....

for(int r = 0; r < p; r++){
    scanf("%lf", &n[r]);
}

for(i = 0; i < p; i++){
    sum += n[i];
}
m = sum / p;

invokes undefined behavior.

Initialize p like f.e.

int p = 5;

Also don't forget to check the return value of scanf() if all items were assigned successfully, like for example:

if(scanf("%lf",&n[r]) != 1) 
{
     fprintf(stderr,"Error at scanning!");
     return 1;
}