i have to create a program that finds the best fit line from a file the user enters that contains the points but we dont know how many points there are so i had to use while(inFile.good()). i made the program and it runs however it is not calculating the correct equation. i think i made a mistake where when the file reads the points in the while loop, for example how do i know that each statement is being performed after each x anf y value is being read from the file.
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<cmath>
#include<iomanip>
usingnamespace std;
int main()
{
ifstream inFile;
cout << "Enter a file name containing the points: ";
string inputFilename;
cin >> inputFilename;
inFile.open(inputFilename.c_str());
double sumx=0;
double sumy=0;
double sumxs=0;
double sumys=0;
double sumxy=0;
int n=0;
double x, y;
int c;
char p;
while(inFile.good())
{
inFile >> c >> x >> p >> y; //how do i know that after each x and y value is entered
//the program completes the following statements to keep
//track of sums and how many points there are?
sumx+=x; //to find the sum of x values
sumy+=y; //to find the sum of y values
sumxs+=pow(x,2); //to find the sum of x squared values
sumys+=pow(y,2); //to find the sum of y sqaured values
sumxy+=(x*y); //to find the sum of product of x and y values
n++; //to keep track of how many points there are to find averages
}
double avgx=sumx/n; //to find the average of x values
double avgy=sumy/n; //to find the average of y values
double avgxs=sumxs/n; //to find the average of x squared values
double avgys=sumys/n; //to find the average of y squared values
double avgxy=sumxy/n; //to find the average of product x and y values
double a=(avgxy-avgx*avgy)/(avgxs-pow(avgx,2)); //to calculate a
double b=avgy-(a*avgx); //to calculate b
cout << "The best fit line is given by y="
<< a << "x" << showpos << b <<endl; //y=ax+b
system("PAUSE");
return 0;
i think the problem is the periods in the file, cause when i changed them to commas my program would give my the correct answer, so how does the program read periods? is it a char? or something else?
'.' symbol is decimal separator. 2.2 is read as single floating point number.
And anyway, you should loop on input operations or check stream state right after reading:
1 2 3 4 5 6 7 8 9
while(inFile >> c >> x >> p >> y) {
//...
}
//or
inFile >> c >> x >> p >> y;
if(!infile)
break;