我以为我已经弄清楚了,并且我非常有信心它会起作用。不幸的是,它没有。
下面的代码应该返回平均值、输入的值的数量,然后计算 std Var。我让它返回平均值和计数,但 std var 结果已关闭。使用值 5、6、8 和 9 我应该得到 std var 1.83 的结果,我得到的结果与 7.17 相差甚远。
我知道我的错误在于我计算 std Dev 的方式,但我很确定我做对了。
这是我的代码:
/**
This class is used to calculate the average and standard deviation
of a data set.
*/
public class DataSet{
private double sum;
private double sumSquare;
private int counter;
/**Constructs a DataSet object to hold the
* total number of inputs, sum and square
*/
public DataSet(){
sum = 0;
sumSquare = 0;
counter = 0;
}
/**Adds a value to this data set
* @param x the input value
*/
public void add(double x){
sum = sum + x;
sumSquare = sumSquare + x * x;
counter++;
}
/**Calculate average of dataset
* @return average, the average of the set
*/
public double getAverage(){
double avg = sum / counter;
return avg;
}
/**Get the total inputs values
* @return n, the total number of inputs
*/
public int getCount(){
return counter;
}
public double getStandardDeviation(){
double sqr = sumSquare / counter;
double stdDev = Math.sqrt(sqr);
return stdDev;
}
}
这是我的跑步者计划:
import java.util.Scanner;
class DataSetRunner
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
DataSet data = new DataSet();
boolean done = false;
while (!done)
{
System.out.println("Enter value, Q to quit: ");
String userInput = input.next();
if (userInput.equalsIgnoreCase("Q"))
done = true;
else
{
double x = Double.parseDouble(userInput);
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Count = " + data.getCount());
System.out.println("The Standard Deviation is = " + data.getStandardDeviation());
}