为什么我在C ++中得到分段错误?

时间:2017-05-03 09:14:50

标签: c++

我正在尝试使用旋转编写高斯消除程序,我似乎无法将任何值输入到我的矩阵中。代码编译但在我输入矩阵a和向量b后,我得到分段错误(核心转储)错误消息。我不知道为什么我会这样做。有什么想法吗?

#include<iostream>

int main(int argc, char* argv[])
{
    int n;

    std::cout << "Enter dimension \n";        
    std::cin >> n;     

double** a = new double*[n];
double** A = new double*[n];
double* u = new double[n];
double* b = new double[n];

for(int i = 0; i < n; i++)
{
    a[i] = new double[n];
    A[i] = new double[n+1];
}

std::cout << "Enter the elements of the matrix row-wise:\n";
for(int i = 0; i < n; i++)
{
    for(int j = 0; j < n; j++)
    {
        std::cin >> a[i][j];
    }    
}


std::cout << "Enter b " << "\n";
for(int i = 0; i < n; i++)
{
    std::cin >> b[i]; 
}

for(int i = 0; i < n; i++)
{
    for(int j = 0; j < n; j++)
    {
         A[i][j] = a[i][j];
    } 

}


for(int j = 0; j <= n; j++)
{
    A[j][n] = b[j];
}



for (int i = 0; i < n; i++)
{
    for (int k = i+1; k < n; k++)
    {
         if (A[i][i]<A[k][i])
         {
             for (int j = 0; j <= n; j++)
             {
                double temp=A[i][j];
                A[i][j] = A[k][j];
                A[k][j] = temp;
             }
         }

    }

}                    

for (int i = 0; i < n; i++)
{
    for (int k = i+1; k < n; k++)
    {
        double t = ((double)(A[k][i]))/((double)(A[i][i]));
        for(int j = 0; j <= n; j++)
        {
            A[k][j] = A[k][j] - t*A[i][j]; 
        }

    }

}            


for (int i = n-1; i >= 0; i--)                
{                        
    u[i] = A[i][n];                
    for(int j = i+1; j< n; j++)
    {
         if (j != i)
         {
             u[i] = u[i]-A[i][j]*u[j];
         }

    }

    u[i] = u[i]/A[i][i];           
}

std::cout << "Solution" << "\n";

for(int i = 0; i < n; i++)
{
     std::cout << u[i] << "\n";  
}


return 0;
}

1 个答案:

答案 0 :(得分:0)

您正在为其中一个阵列编制索引。

更改代码

for(int j = 0; j <= n; j++)
{
    A[j][n] = b[j];
}

for(int j = 0; j < n; j++)
{
    A[j][n] = b[j];
}