0

How does this calculation make sense?

#include <cs50.h>
#include <stdio.h>

int main(void) {
int n;

do {
    n = GetInt();
} while (n < 1);

int ages[n];

for (int i = 0; i < n; i++) {
    printf("age of person #%i: ", i+1);
    ages[i] = GetInt();
}

printf("time passes ...\n");

float numPeople = sizeof(ages), sum = 0;
for (int i = 0; i < numPeople; i++) {
    sum += ages[i];
}

printf("the average age is %.1f\n", (sum / numPeople)); 
}

output:

output

1

Figured it out.

sizeof gives the size in bytes. simple fix: sizeof(arr)/sizeof(arr[0]) gives the number of elements in the array.

2
  • But you alredy have number of elements in your n variable. Why don't you use it? Jan 29 '15 at 22:12
  • As said, you already have the number of elements in your variable n ;)
    – Ahmed
    Jun 28 '15 at 19:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .