Thursday, July 30, 2009

C++ help please!?

Basically I'm making a program that asks users to input the number of points they want to enter, and then asks for the x value and y value of these points to calculate the slope and y-intercept, and further find the linear regression of the graph.





I'm at something like this:





#include %26lt;iostream%26gt;


#include %26lt;cmath%26gt;


#include %26lt;iomanip%26gt;


using namespace std;





int main()


{


int n;


double array1[100];


double array2[100];





cout%26lt;%26lt;"Enter the number of points: \n";


cin%26gt;%26gt;n;





while (n%26lt;=1)


{


cout%26lt;%26lt;"Please enter a different number of points: \n";


cin%26gt;%26gt;n;


}





for(int k=1; k%26lt;=n; k++)


{


cout%26lt;%26lt;"Enter the value of the x coordinate: \n";


cout%26lt;%26lt;"x_"%26lt;%26lt;k%26lt;%26lt;endl;


cin%26gt;%26gt;array1[100];





cout%26lt;%26lt;"Enter the value of the y coordinate: \n";


cout%26lt;%26lt;"y_"%26lt;%26lt;k%26lt;%26lt;endl;


cin%26gt;%26gt;array2[100];


}





return 0;


}





And I get an error"Run-Time Check Failure #2 - Stack around the variable 'array2' was corrupted."


How are the numbers assigned in the array to access them to create the formula for the slope, and how do I fix this error?

C++ help please!?
array1 and array2 you can only have the index from 0 to 99. basically your program is buffer overflow. inside the loop you should code like cin %26gt;%26gt; array1[k-1] (if that's what you want, as as the array2). Good luck.
Reply:I think you got the logic all wrong, you may want to reconsider this order. You don't really need arrays to hold 4 numbers total. All you need to calculate the slope and y-intercept are 4 numbers, (x1, y1), (x2, y2)





You also have syntax errors: what's the k doing there? (example: cout%26lt;%26lt;"y_"%26lt;%26lt;k%26lt;%26lt;endl;


you never defned 'k'.....





The easiest would be a straigt forward enter the first point as (x, y)


do a cin%26gt;%26gt;x1%26gt;%26gt;y1;





prompt for second point as (x,y)


do cin%26gt;%26gt;x2, y2;





now you have all you need to calculate slope and y-intercept.


you have to define these. something like


double s;


int y_intercept;





s = (x2-x1)/(y2-y1);





then do the y intercept.





then output these values


cout%26lt;%26lt;"the slope with the given points is " %26lt;%26lt;s%26lt;%26lt;endl;


cout%26lt;%26lt;"the y intercept with the given points is " %26lt;%26lt;y_intercept%26lt;%26lt;endl;





Send me an email if you want more help with it.


No comments:

Post a Comment