A function that returns the mean and sum of elements.

Asked 2 months ago, Updated 2 months ago, 3 views

I would like to output the average and sum of the elements from 0th to n-1, but I don't know how to do it.
I think I understand how to write programs like 1+2+3+4+...+n, but I didn't know how to write programs that let the terminal input numbers randomly and output the sum and mean.
I entered the program as follows, but I probably thought the sumIntArray part was wrong, and I didn't know what to program in /......../.

void readIntArray (inta[], int size)
{
    inti;
    for(i=0;i<size;i=i+1){
        printf("%dth?", i=i+1);
        scanf("%d", & a[i]);
    }
    printf("%d", a[i]);
}

void sumIntArray(inta[], int size)
{
int sum, i;
for(i=0;i<size;i=i+1){
sum = sum + i;
}
return sum;
}

int main (void)
{
  int data [100], n, sum;
  double average;

  printf("n=? ");
  scanf("%d", & n);

  readIntArray(data,n);

  sum=sumIntArray(data,n);
  printf("sum=%d\n",sum);

/......................./
  return 0;
} 

The example execution should be as follows:

$./a.out
n = ?5
0th? 2nd.
1st? 3
2nd? 5
Number three? Number seven.
4th? 11
sum = 28
average=5.600000

c

2022-09-30 14:08

1 Answers

Review the program based on the following:

  • Previous question Same as @metropolis's comment on about storing elements in reverse order
    printf("%dth?",i=i+1); in the readIntArray() function is printf("%dth?",i+1);
  • readIntArray()The last printf("%d", a[i]) of the function does not make sense
  • sumIntArray()Function definition and processing incorrectly
    • Return value is not void but int
    • The variable sum has not been initialized to 0
    • forModify the processing in the loop to add index values to add data
  • doubleCast the total value and the number of data in double to get the average expressed by the value
  • double To specify how to display the value in printf(), view your reference book or search the web
  • Return value is not void but int
  • The variable sum has not been initialized to 0
  • forModify the processing in the loop to add index values to add data


2022-09-30 14:08

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.