Return to Existing Everywhere Main Page

C++ Information on a Linear Equation

 

The following C++ program calculates the coefficients of a linear equation given two point in the coordinate plane. The coefficient for the x variable is calculated by subtracting the x values of the points. This corresponds to the horizontal distance component of a vector between the points. The coefficient for the y variable is calculated by subtracting the y values which represents the vertical distance between the points. The constant for the equation is also calculated using the points.

The linear equation is displayed in general or standard form. The signs for the coefficients are calculated in a display method for the Line class. The linear equation itself is implemented as a class with a constructor and two other methods.

#include 
#include 

using namespace std;

class Line
{
private:
	float a;
	float b;
	float c;
	float d;
	float A;
	float B;
	float C;

public:
    Line()
    {
        a = 1;
	    b = 2;
    	c = 3;
	    d = 5;      
    }
       
	void calculateCoefficients()
	{
		A = d - b;
		B = a - c;
		C = b * c - a * d;
	}

	void displayEquation()
	{
        string signB;
        string signC;
        
        signB = (B>0)?"+":"";
        signC = (C>0)?"+":"";
        
		cout << A << "x" << signB << B << "y" << signC << C << "=0" << endl;
	}
};

int main(int argc, char *argv[])
{
    Line line1;
	line1.calculateCoefficients();
	line1.displayEquation();
    
    system("PAUSE");
    return EXIT_SUCCESS;
}