I'm trying to make a little program to calculate standard deviation for practice. My problem seems to be the first while statement in my main function.
I’m a little rusty at this and I can’t figure out why I don’t leave the while statement after the user hits enter.
Don’t mind my greenness. Still learning.
#include <stdio.h>
#include <math.h>
#define arraySize 100
double standardDeviation(int, double*);
int main(void){
double array[arraySize];
double result;
int i=0;
int count=0;
printf("Enter up to %d data separated by spaces then hit enter:\n\n",arraySize);
while(i<arraySize && array[i]!='\n'){
scanf("%lf",&array[i]);
i++;
count++;
}
result=standardDeviation(count, array);
printf("The standard deviation of your data is: %lf",result);
return 0;
}
double standardDeviation(int count, double* firstDatum){
int i=0,j=0;
double standDev=0;
double standDevArray[arraySize];
double sum=0,sum2=0;
double mean=0,variance=0;
while(i<count){
sum=sum + firstDatum[i];
//printf("%lf", sum);
i++;
}
mean=sum/count;
//printf("The mean is: %lf", mean);
while(j<count){
standDevArray[j] = (mean - firstDatum[j]) * (mean - firstDatum[j]);
sum2=sum2+standDevArray[j];
j++;
}
variance=sum2/count;
standDev=sqrt(variance);
return standDev;
}
array[i]is adouble. While it isn't wrong to compare that with'\n', it is weird and unusual — write13.0rather than'\n', probably (but even more likely, that test is superfluous). Also, the value ofiis one beyond the last initialized entry inarray— you've got undefined behaviour (UB) in your code. You should be checking the result of thescanf()call, too.%lfformat skips white space, including newlines. You might (probably would) exit the loop if you typed 13 as a value. Detecting newlines inscanf()is hard. You have to be doing character input (%c,%s,%[…]) to get a newline into your program's data.while(i<arraySize && scanf("%lf",&array[i]) == 1) { ... }'\n'is typically 10, not 13. ('\r'is typically 13.)