loops for best fit line calculation

I'm writing this program to calculate the best fit line. It's not finished. I'm doing it step to step to make sure it runs so I don't get lots of errors and totally freak out at the end. Right now it runs fine, but something is really off with the calculations I have so far. The loop for the input works great, but the averages are really wrong, and the for the sum of squares calculation it is only calculating the square of the last value. Where am I going wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cmath>

using namespace std;

double avg(double[], int);
double sumsq(double[], int);

int main ()
{
	int n;
	cout << "How many points do you want to plot? ";
	cin >> n;
	
	double x[n];
	double y[n];
	
	for (int i=1; i<=n; i++)
	{
		cout << "Please enter the value for x " << i << ": ";
		cin >> x[n];
		cout << "Please enter the value for y " << i << ": ";
		cin >> y[n];
	}
	
	cout << avg(x,n) << endl; 
	cout << avg(y,n) << endl;
	cout << sumsq(x,n) << endl;
	cout << sumsq(y,n) << endl;
	
	return 0;
}

double avg(double z[], int n)
{
	double sum=0;
	
	for (int i=1; i<=n; i++)
	{
		sum+=z[i];
	}
	
	return sum/n;
}

double sumsq(double z[], int n)
{ 
	double sum=0;
	double sumsq=0;
	
	for (int i=1; i<=n; i++)
	{
		sumsq=sum+(z[i]*z[i]);
	}
	
	return sumsq;
}
		
for (int i=1; i<=n; i++) is wrong.
The indices of an array go from 0 to 1 less than its size.

So your for loop should be
for (int i = 0; i < n; i++)
I originally had it at i=0 but the answers were wrong and I thought since in main my loop starts at 1 maybe I should change it. I still doesn't make a difference.
Oh, I just noticed, you're technically not allowed to have variable length arrays like
double x[n];

If you want an array with variable length, use std::vector<double>.
(you could also do something like double* x = new double[n], but why bother when we have std::vector<double>)

Also:
18
19
20
21
22
23
24
for (int i=1; i<=n; i++) // Should be for (int i = 0; i < n; i++)
{
    cout << "Please enter the value for x " << i << ": ";
    cin >> x[n]; // Should be cin >> x[i];
    cout << "Please enter the value for y " << i << ": ";
    cin >> y[n]; // Should be cin >> y[i];
}


Also, your "sumsq" function doesn't make any sense at all.
You're not summing anything in it....
Everything else works now except for the square sums formula. If my variable for the loop is z, I basically want it to say to square each z[i] and add them together. But I can't figure out how to code that.
You code it pretty much just like your "avg" function, except instead of adding z[i], you add z[i]*z[i].
(and you don't divide by n at the end, of course)
Topic archived. No new replies allowed.