eric eric eric eric - 2 months ago 6
C Question

Issues with if statements in 'CalAverage' function

I created two if statements to go inside the linked list and check to see how many numbers are above the average and to see how many are below the average. When I run the program to my understanding the if statements are only counting one number. Also, when the program runs, only one of the if statements are called, not both. Maybe I am overlooking something?

double CalAverage (NewNumber *start){

int res;
double average = 0;
double total = 0;
int n = 1;
int x = 1;
int y = 1;

/*if (res != 1){
fprintf(stderr, "Something bad happened in CalAverage()\n");
return add;
}*/
while (start->next){
average += start->newNum;
start = start->next;
++n;
}
average += start->newNum;
total = average/n;
if(total < start->newNum){
++x;
printf("Numbers greater than average: %d\n",x);
}else if(total > start->newNum){
++y;
printf("Numbers less than average: %d\n", y);
}
printf("The average is: %lf\n",total);
return total;
return x;
return y;

}

Answer

first, you are losing the pointer to the start of the list by overriding it in the while loop. copy it aside before you start to loop over it.

second, put the if statements in another loop (after re-asigning the start of the list) to count the below/above average.

double CalAverage (NewNumber *start){

    double average = 0;
    double sum = 0;
    int n = 0;
    int x = 0;
    int y = 0; 

    NewNumber *temp = start;

    while (temp){
        sum += temp->newNum;
        temp = temp->next;
        ++n;
    }

    average = sum / n;

    temp = start;

    while (temp){

        if(average < temp->newNum){
            ++x;
        }else if(average > temp->newNum){
            ++y;
        }

        temp = temp->next;
    }

    printf("The average is: %lf\n",average);
    printf("Numbers greater than average: %d\n",x);
    printf("Numbers less than average: %d\n", y);
    return average; 
}
Comments