Simple algebraic linear equation

//I have no idea why this isn't working. Logically I'd figure both the formulas would work but they don't. Try and get a negative slope, and then type y to find the y-intercept. When i get a positive slope, the y-intercept is correct, however if i get a negative slope, the y-intercept is way off.


#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
//This formula is correct
cout << "This program will help you find the slope of a normal line." << endl;
cout << "Please insert a value for each variable respectively." << endl;
cout << "y2, y1, x2, x1: ";
double y2, y1, x2, x1;
cin >> y2 >> y1 >> x2 >> x1;
double slope = (y2-y1)/(x2-x1);
cout << setprecision(2) << showpoint << fixed << "M = " << slope << endl;

cout << "Now would you like to find the y-intercept? <y/n>" << endl;
char answer;
cin >> answer;


if(answer == 'y')
{
//Negative formula is incorrect at the moment.
double sX = (x2 * slope);
if(sX < 0)
{
double b = (y2 + sX);
cout << "b = " << setprecision(2) << showpoint << b << endl;
}
else if(sX > 0)
{
double b = (y2 - sX);
cout << "b = " << setprecision(2) << showpoint << b << endl;
}
}
else if(answer == 'n')
cout << "Have a nice day." << endl;

system("pause");
return 0;
}
I guess it makes more sense to use in both cases b=(y2-sX), since sX is negative.
Not necessarily though. What if you had a positive x2 and a negative slope, or vise versa, and multiplied the two to end up with a negative integer? to solve for b you would have to add it to the other side would you not?
Your formula should not depend upon whether the slope is positive or negative, so the fact that
you have an if() statement means your algorithm is wrong.

The general formula for a line is
y - y0 = m( x - x0 )

You computed m already. You have two points to choose from for ( x0, y0 ).

The y-intercept of a line with formula y = mx + b is b.
So solve for b. In the above equation, y0 and x0 are constants, so

y = mx + ( y0 - mx0 )

So b = y0 - mx0.

This is the formula regardless of the sign of y0, x0, or m.

Topic archived. No new replies allowed.