无法使编码解决线性方程

时间:2015-06-20 11:49:45

标签: c visual-c++

所以我做了一个程序来解决3的线性方程,但由于某种原因它没有给我适当的答案,我做了我的研究,但似乎无法找到我的编码错误

我正在使用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();
    }

1 个答案:

答案 0 :(得分:1)

整数师。

使用矩阵解决方案,即使使用整数输入,解决方案也总是需要浮点数学。

// 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]);