I got the correct results of deviation but something wrong with the value sum.
Really confused about it.
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace std;
void meanAndStDev(int size, char *arr,float *Mean,float *StDev){
float sumSqr=0.0;
float sum=0.0;
for(int i=0;i<size;i++){
sum = sum +arr[i];
}
for(int i=0;i<size;i++){
sumSqr = sumSqr+arr[i]*arr[i];
}
*Mean = sum/size;
*StDev = sqrt(sumSqr/size - pow(*Mean,2));
}
int main(){
float Mean,StDev;
int size;
char arr[size];
cout<< "Please type in how many numbers you want"<<endl;
cin>>size;
cout<<"Please type in the numbers"<<endl;
for(int i=0;i<size;i++){
cin>>arr[i];
}
meanAndStDev(size,arr,&Mean,&StDev);
cout<<"The mean is: "<<Mean<<endl;
cout<<"The Standard Deviation is: "<<StDev<<endl;
return EXIT_SUCCESS;
}
New problem raised up.
Please type in how many numbers you want
7
Please type in the numbers
1 2 3 4 5 6 7
The mean is: -nan
The Standard Deviation is: -nan
May I ask why you delete the array? Here is the new code which run quite well now.
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace std;
void meanAndStDev(int size, float *arr,float *Mean,float *StDev){
float sumSqr=0.0;
float sum=0.0;
for(int i=0;i<size;i++){
sum = sum +arr[i];
}
for(int i=0;i<size;i++){
sumSqr = sumSqr+arr[i]*arr[i];
}
*Mean = sum/size;
*StDev = sqrt(sumSqr/size - pow(*Mean,2));
}
int main(){
float Mean,StDev;
int size;
float arr[size];
cout<< "Please type in how many numbers you want"<<endl;
cin>>size;
cout<<"Please type in the numbers"<<endl;
for(int i=0;i<size;i++){
cin>>arr[i];
}
meanAndStDev(size,arr,&Mean,&StDev);
cout<<"The mean is: "<<Mean<<endl;
cout<<"The Standard Deviation is: "<<StDev<<endl;
return EXIT_SUCCESS;
}