Yyh - 6 months ago 30

C Question

`#include<stdio.h>`

#include<math.h>

int main()

{

int n;

scanf("%d",&n);

int i=0,sum=0,average=0;

int num[100]={0};

double dvalue[100]={0.0};

double variance=0.0,s=0.0;

for(i=0;i<n;i++){//I just know this method to get the number array;

scanf("%d",&num[i]);

sum+=num[i];

}

average=sum/n;

for(i=0;i<n;i++){

dvalue[i]=num[i]-average;

dvalue[i]=pow(dvalue[i],2.0);//to get the (x-average）……2

variance+=dvalue[i];

}

s=sqrt(variance);

return 0;

}

this is my code,but it can't get the right answer.I am a new learner and this is the first time I seek help via stackoverflow I can't get the output why?

Thanks for every one .I actually debug at first ,but I can't know how to modify it ,sincerely thanks again

Answer

There were two things to correct:

1. type of `average`

should be `double`

2. you have taken the variance incorrectly. after taking the sum of (x- average) you should divide it by `n`

```
#include<stdio.h>
#include<math.h>
int main()
{
int n;
scanf("%d", &n);
int i = 0, sum = 0;
double average = 0;
int num[100] = { 0 };
double dvalue[100] = { 0.0 };
double variance = 0.0, s = 0.0;
for (i = 0; i < n; i++) { //I just know this method to get the number array;
scanf("%d", &num[i]);
sum += num[i];
}
printf("sum %d\n", sum);
average = sum;
average = average / n;
printf("average %lf\n", average);
for (i = 0; i < n; i++) {
dvalue[i] = num[i] - average;
dvalue[i] = pow(dvalue[i], 2.0); //to get the (x-average)……2
variance += dvalue[i];
}
variance = variance / n; // population variance
s = sqrt(variance);
printf("varience %lf\n", variance);
printf("Population Standard deviation %lf", s);
return 0;
}
```

edited the answer according to @chux advice