Larry the Guy
Larry the Guy

Reputation: 1

Standard Deviation c++ Formula advice

I have this assignment in which i will show the prompt for it:

Write a program that reads in a set of test score data from the user. (Test scores should be entered in decimal form to represent the percentage grade). Once the user has finished entering the test scores (entering -1 will signal the end of input), print out the number of tests entered, the average of the tests, and the standard deviation. Use the following formula (Welford’s method) to calculate the standard deviation: (Standard Deviaton Formula)

You can compute this quantity by keeping track of the count (number of tests), the sum, and the sum of squares as you process the input values. Note: Although there are other ways to calculate the standard deviation, please use this method. This method is used since it only requires one pass of the data. Do not use arrays or vectors.

Now the code below is what I have so far. In the terminal, I'm getting wrong numbers for the average and Std. Deviation outputs (Terminal Output). Is there anything wrong with my math? Any help is appreciated. EDIT: Here is the data I'm using and the expected results I should be getting:

 1.  67.8
 2.  95.6
 3.  89.5
 4.  76.7
 5.  71.3
 6.  83.2
 7.  90.6
 8.  56.1
 9.  98.6
 10. 85.2

result:

Number of Test Scores: 10
Average : 81.46
Std. Deviation: 13.39

Code

#include <iostream>
#include <cmath>

using namespace std;

int main()
{

    double sum = 0;
    double sumSq = 0;
    double grade = 0;
    int numtests = 0;

    cout << "Enter the test scores. Once finished, enter -1 to end input.\n";
    cin >> grade;

    while (grade != -1)
    {
        cin >> grade;
        sum = sum + grade;
        sumSq = sumSq + pow(grade, 2);
        numtests++;
    }

    double average = (sum / numtests);
    double std = (sumSq - numtests * pow(average, 2) / (numtests - 1));

    cout << "The number of scores: " << numtests << "\n";
    cout << "Average: " << average << "\n";
    cout << "Std. Deviation: " << std << "\n";

    return 0;
}

Upvotes: 0

Views: 467

Answers (1)

Frank Merrow
Frank Merrow

Reputation: 1009

You've written the function so "-1" is part of the calculation which isn't what you want. I could fix it for you, but I think you can take it from that hint. And now that I look again, the first number is NOT part of your calculation.

Upvotes: 4

Related Questions