Reputation: 123
My Standard deviation in this program is outputting as 0 and I don't know what I'm doing wrong. I've been stuck on this for hours, please help.
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers do you want to calculate?");
int n = scan.nextInt();
double a[] = new double[(int) n]; // casting n to a double
double sum = 0.0;
double sd = 0.0;
System.out.println("Fill in the values for all " + n + " numbers.");
for(int i = 0; i < a.length; i++)
{
a[i] = scan.nextDouble();
sum = sum + a[i];
}
double average = sum/a.length;
for(int i = 0; i < a.length; i++)
{
a[i] = Math.pow((a[i]-average),2); // need help here
}
System.out.println("The Mean of the " + n +" numbers is " + average);
System.out.println("The Standard Deviation of the " + n + " numbers is " + sd);
}
Upvotes: 0
Views: 35
Reputation: 13
Here is a fiddle
Also I have modified your code which should work now and give you correct result.
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers do you want to calculate?");
int n = scan.nextInt();
double a[] = new double[(int) n]; // casting n to a double
double sum = 0.0;
double sqrSum = 0.0;
double sd = 0.0;
System.out.println("Fill in the values for all " + n + " numbers.");
for(int i = 0; i < a.length; i++)
{
a[i] = scan.nextDouble();
sum = sum + a[i];
}
double average = sum/a.length;
//Perform the Sum of (value-avg)^2
for(int i = 0 ; i < a.length ; i++)
{
sqrSum = sqrSum + Math.pow( a[i] - average, 2);
}
sd = Math.sqrt(sqrSum / (a.length - 1));
System.out.println("The Mean of the " + n +" numbers is " + average);
System.out.println("The Standard Deviation of the " + n + " numbers is " + sd);
}
Upvotes: 1