I tried everything to get standard deviation to work. I'm trying to make a program that gets grades of students (count decided by user) and it calculates the mean of the grades and also the standard deviation. It calculates the mean fine but for standard deviation it gives "7712160851427328.00"
#include <stdio.h>
int main(){
int i;
int j;
int count;
int grade = 0;
int grades[5] = {0}; //Init
int sum = 0;
float deviation_sum;
float mean;
float standard_deviation;
printf("Give Count: ");
scanf("%d", &count);
for(i = 0; i < count; i++){
printf("Give %d grade: ", (i+1));
scanf("%d", &grade);
switch(grade){
case 0:
grades[0]++;
break;
case 1:
grades[1]++;
break;
case 2:
grades[2]++;
break;
case 3:
grades[3]++;
break;
case 4:
grades[4]++;
break;
case 5:
grades[5]++;
}
sum += grade;
}
mean = sum/count;
printf("mean: %.2f \n", mean);
for(i = 0; i <= 5; i++){
while(grades[i] == 0){
i++;
}
for(j = 0; j < grades[i]; j++){
deviation_sum += (i-mean)*(i-mean);
printf("%d,%d\n",i,j);
}
}
standard_deviation = sqrt(deviation_sum /count - 1);
printf("deviation: %.2f\n", standard_deviation);
}
I think the problem is in the last for loop just can't figure it out.
You'll have to initilize deviation_sum to zero. Otherwise it takes garbage value as its initial value