c - averaging while looping, the sum won't clear and thus keeps adding numbers from previous loop entry -


 #include <stdio.h>   int main () {  int days, flights, t, b;  float length, mean, sum;   printf("how many days has dragon been practicing?\n");  scanf("%d", &days);   for(t=1; t<=days; t++) {     printf("how many flights completed in day #%d?\n", t);     scanf("%d", &flights);     for(b=1; b<=flights; b++) {         printf("how long flight #%d?\n", b);         scanf("%f", &length);         sum+=length;      }         mean = sum/flights;         printf("day #%d: average distance %.3f.\n", t, mean);  }  } 

the sum used calculate mean supposed number 1 iteration of loop added together. instead sum used numbers new iteration , old iteration added together.

if understood problem correctly, after last printf() statement, should reset sum 0, sum = 0;.

that said, major issue in code that, you're using sum (an automatic storage local variable) while uninitialized. should initializing sum value (0, maybe) before making use (sum+=) of it. otherwise, it invokes undefined behavior.

to quote c11 standard, chapter §6.7.9

if object has automatic storage duration not initialized explicitly, value indeterminate. [...]


Comments