Ste Rose
Ste Rose

Reputation: 33

Program returns incorrect values (C++)

I've wrote a simple code to play around with two dimensional arrays, the aim of the code being to solve two linear simultaneous equations using a matrix method (expressing the coefficients in a square matrix, computing the inverse, multiplying the inverse by the output of each of the equations to find the results of the two variables). There are no warnings when the code compiles, so, I have no idea what the problem could be.

#include <iostream>
using namespace std;

double determinant(double parameterMatrix[2][2])
{
    return parameterMatrix[1][1] * parameterMatrix[2][2] - parameterMatrix[1][2] *     parameterMatrix[2][1];
}

void invertMatrix (double parameterMatrix[2][2], double inverseMatrix[2][2])
{
    double parameterDeterminant = determinant(parameterMatrix);

    inverseMatrix[1][1] = parameterMatrix[2][2] / parameterDeterminant;
    inverseMatrix[1][2] = - parameterMatrix[1][2] / parameterDeterminant;
    inverseMatrix[2][1] = - parameterMatrix[2][1] / parameterDeterminant;
    inverseMatrix[2][2] = parameterMatrix[1][1] / parameterDeterminant;
}

int main()
{
    double resultVector[2];
    double coefficientMatrix[2][2];

    cout << "Enter equations of lines, which are of the form ax+by=c" << endl;

    cout << "a = "; cin >> coefficientMatrix[1][1];
    cout << "b = "; cin >> coefficientMatrix[1][2];
    cout << "c = "; cin >> resultVector[1];

    cout << "a = "; cin >> coefficientMatrix[2][1];
    cout << "b = "; cin >> coefficientMatrix[2][2];
    cout << "c = "; cin >> resultVector[2]; cout << endl << endl;

    double inverseCoefficientMatrix[2][2];
    invertMatrix(coefficientMatrix, inverseCoefficientMatrix);

    double x = inverseCoefficientMatrix[1][1] * resultVector[1] + inverseCoefficientMatrix[1][2] * resultVector[2];
    double y = inverseCoefficientMatrix[2][1] * resultVector[1] + inverseCoefficientMatrix[2][1] * resultVector[2];

    cout << "The lines intersect at the point (" << x << ", " << y << ")" << endl;
    return 0;
}

If you try it with a simple example, e.g, x + 2y = 3 and 3x + 2y = 1, which should return x = -1 and y = 2, the values it returns are -0.5 and 0.1875. I've been inserting lines into the code to print out the values of everything at each stage, and I've came to the conclusion that the determinant function is changing the value of resultVector, but I have no idea why, so any help would be greatly appreciated.

Upvotes: 1

Views: 119

Answers (2)

user995502
user995502

Reputation:

In C/C++ array indices start from 0 not from 1. So double a[2] is a[0] and a[1]. There is no a[2]. (well there is but it is not yours)

Upvotes: 4

Nate Hekman
Nate Hekman

Reputation: 6657

Arrays are zero-based in C++:

double determinant(double parameterMatrix[2][2])
{
    return parameterMatrix[0][0] * parameterMatrix[1][1] - parameterMatrix[0][1] * parameterMatrix[1][0];
}
etc...

Upvotes: 1

Related Questions