Home > Mobile >  why is my code of calculating average from an array not working?
why is my code of calculating average from an array not working?

Time:10-19

do I had a large sample size so I made a big array and read the file's data into it but my code is not compiling for some reason

#include <stdio.h>

int main(){
    FILE *file;
    file = fopen("elephantArray.txt", "r");
    if( file == NULL){
        fprintf(stderr, "Can't open input file in.list!\n");
        exit(1);
    }
    int weight;
   int weightSet[10000];
   int i =0;
   while(fscanf(file, "%d\t", &weightSet[i]) != EOF){
    printf("%d\n", weightSet[i]);
    i  ;
   }
   fclose(file);
   int j =0;
   int sum=0;
    int size=0;
   for(int j=0; j<10000;j  ){

    while(weightSet[j]!=NULL){
        sum = sum   weightSet[j];
        size  ;
    }
   }
    int average= sum/size;
    printf(average);
    return 0;



}

I am getting the error expected const char but argument is of int type and I am confused why?

CodePudding user response:

This line

while(fscanf(file, "%d\t", &weightSet[i]) != EOF){

is not 100% correct. You should

  1. Check for i not exceeding array size

  2. Compare scanf return value with 1

  3. Drop the \t as it doesn't do anything useful.

So do

while(i < 10000 && fscanf(file, "%d", &weightSet[i]) == 1){

The reason for "error expected const char but argument is of int type" is simple:

printf(average); ---> printf("%d\n", average);

That said, your code for calculating the sum is wrong, i.e. this code will not work:

   for(int j=0; j<10000;j  ){

    while(weightSet[j]!=NULL){     // This will be an endless loop...
        sum = sum   weightSet[j];
        size  ;
    }
   }

Instead use i in the for loop as i holds the number of valid array elements:

   sum = 0;
   for(int j=0; j<i; j  ){
        sum = sum   weightSet[j];
   }
   if (i != 0) {
       int average = sum/i;
       printf("%d\n", average);
   }
   else
   {
       puts("No integers found in the file");
   }

BTW: Notice that calculating an average as an integer may give some surpricing result.

CodePudding user response:

#include <stdio.h>

int main(){
    FILE *file;
    file = fopen("elephantArray.txt", "r");
    if( file == NULL){
        fprintf(stderr, "Can't open input file in.list!\n");
        exit(1);
    }
    int weight;
    int weightSet[10000];
    int i = 0;
    while(fscanf(file, "%d\t", &weightSet[i]) == 1){
        printf("%d\n", weightSet[i]);
        i  ;
    }
    fclose(file);
    int j =0;
    int sum=0;
    int size=0;
    for(j=0; j<i;j  ){
        sum = sum   weightSet[j];
    }
    if (i != 0) {
       int average= sum/i;
       printf("%d\n", average);
    }
    else
    {
       puts("No integers found in the file");
    }
    int average= sum/size;
    printf("%d\n", average);
    return 0;
}
  •  Tags:  
  • c
  • Related