Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Need help fixing variance code

$
0
0
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int main()
{
	ifstream infile("number.txt");
	if(infile.good())
	{
		int number = 0, sum = 0, sum2 = 0, count = 0;
		double average = 0.0, variance = 0.0;
		
		while (infile >> number)
			{ 
				if (number >= 0)
				{
				sum += number;
				count++;
				average = (double)sum / count;	
				variance = pow(((double)number-average), 2);
				}
			}
		cout.setf (ios :: fixed);
		cout.setf (ios :: showpoint);
		cout.precision(4);
		cout << "The average is: " << average << endl;
		cout << "The variance is: " << variance << endl;
		cout << "The standard deviation is: " << sqrt(variance) << endl;
	}
	else 
	{
		infile.fail();
		cout << "Oops" << endl;
	}
	infile.close();
	return 0;
}



Correct Output:
Avg=47.59
Var=874.3858
SD=29.57001

My Output:
Avg=47.59
Var=875.5681
SD=29.59

I am not quite sure where i am messing up. I do know Variance is the (number - average)^2 / count;
but when I add the / count My var and Sd are really low numbers like 8.7, and 2.9.

Here are the numbers
25
5
64
47
92
30
63
67
10
33
25
39
58
28
16
57
23
89
38
58
36
40
32
63
8
29
6
96
3
4
89
69
27
86
63
59
47
36
88
3
1
68
97
27
47
88
59
4
32
46
87
100
19
68
15
59
45
6
77
62
89
4
49
32
65
81
68
28
56
25
100
15
5
5
14
18
50
60
65
75
32
31
99
5
88
91
53
27
83
53
87
13
88
85
77
53
35
69
10
18
-1

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>