Home > Software design >  Could anyone help find the problem in this simple c program about averages?
Could anyone help find the problem in this simple c program about averages?

Time:11-19

It just gives 0 as average in the end. no matter what values I put in the list. I guess there's some issue in the avg. I am absolute beginner in c. any help would be appreciated.

#include <stdio.h>
    
int main() {
    int sum, list, total;
    float avg;

    printf("Enter total number of values: ");
    scanf("%d", &total);

    for (list = 0; list < total; list  ) {
        printf("Enter the values: ");
        scanf("%d", &list);
        list  = sum;
    }
    
    avg = (float) sum / (float) total;
    printf("The average of such values shall be: %d", avg);
    
    return 0;
}

CodePudding user response:

#include <stdio.h>

int main() {
    int sum = 0;
    int list = 0;
    int total = 0;
    int counter = 0;
    float avg = 0.0;

printf("Enter total number of values: ");
scanf("%d", &total);

for (; counter < total; counter  ) {
    printf("Enter the values: ");
    scanf("%d", &list);
    sum  = list;
}

avg = (float) sum / (float) total;
printf("The average of such values shall be: %f", avg);

return 0;
}
  1. Your loop condition did not make sense.
  2. Your internal loop was doing list =sum, sum was never being set or entered in as an input
  3. Printing was %d not %f

CodePudding user response:

You're adding sum to list instead of the other way around. So what happens is you're reading a value, storing it into a variable and adding some random value (hopefully 0, since it's not initialized) to it, then overriding that variable with the new value read, and so on and so forth.

for (list = 0; list < total; list  ) {
    printf("Enter the values: ");
    scanf("%d", &list); // reads and stores value into list
    list  = sum;        // list = list   sum
}

Try to switch list = sum to sum = list. It should work:

for (list = 0; list < total; list  ) {
    printf("Enter the values: ");
    scanf("%d", &list); // reads and stores value into list
    list  = sum;        // sum = sum   list
}

Also, as stated before, get in the habit of always initializing values. Specially counters and accumulators (sum, in this case). Some compilers auto-initialize them to 0 in case no value is specified, but some don't, and you run into the risk of having some random trash value stored into your counter/accumulator.

This happens because the compiler must allocate memory space to the variable, and that memory space can have some random trash values in it. So, as a good practice always initialize.

  •  Tags:  
  • c
  • Related