Reputation: 45
So i made a program to solve a linear equation of 3, but for some reason it does not give me the appropriate answer, i have done my research but cant seem to find whats wrong with my coding
I am using visual c++ 2010/ 2015
void linear()
{
int y[3][3], inv[3][3], co[3][3], d[3], sol[3], D = 0, i = 0, j = 0;
char z;
printf("The format for the linear equation is\na1.X + b1.Y + c1.Z = d1\na2.X + b2.Y + c2.Z = d2\na3.X + b3.Y + c3.Z = d3\n");
for (i = 0;i < 3;i++)
{
for (z = 'a';z < 'd';z++)
{
printf("Enter the value for %c%i\n", z, i + 1);
scanf("%i", &y[i][j++]);
}
printf("Enter the valie for D%i\n", i + 1);
scanf("%i", &d[i]);
j = 0;
}
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
co[i][j] = (y[(i + 1) % 3][(j + 1) % 3] * y[(i + 2) % 3][(j + 2) % 3]) - (y[(i + 1) % 3][(j + 2) % 3] * y[(i + 2) % 3][(j + 1) % 3]);
for (i = 0;i < 3;i++)
D += y[i][0] * co[i][0];
if (D == 0)
{
printf("\nThese equations cannot be solved!\n");
return;
}
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
swap(&co[i][j], &co[j][i]);
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
inv[i][j] = co[i][j] / D;
for (i = 0;i < 3;i++)
{
sol[i] = 0;
for (j = 0;j < 3;j++)
sol[i] += inv[i][j] * d[j];
}
printf("The solutions are\nX=%i\nY=%i\nZ=%i\n", sol[0], sol[1], sol[2]);
getch();
}
Upvotes: 1
Views: 64
Reputation: 154255
Integer division.
With matrix solutions, even with integer inputs, invariably the solution will need floating point math.
// int inv[3][3], sol[3];
double inv[3][3], sol[3];
...
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
// inv[i][j] = co[i][j] / D;
inv[i][j] = 1.0 * co[i][j] / D;
...
sol[i] += inv[i][j] * d[j];
...
// printf("The solutions are\nX=%i\nY=%i\nZ=%i\n", sol[0], sol[1], sol[2]);
printf("The solutions are\nX=%e\nY=%e\nZ=%e\n", sol[0], sol[1], sol[2]);
Upvotes: 1