当我将它们作为两个不同的输入文件调用时,如何打印它们?

how can i print two matrices when i call them as two different input file?

本文关键字:文件 调用 何打印 打印 输入 两个      更新时间:2023-10-16

我试图打印两个矩阵,比如矩阵A和B。当我只为矩阵 A 调用一个文本文件时,我的程序就可以了。但是当我调用矩阵 B 的另一个文本文件时,我的程序失败了,留下一个框,上面写着"newQr.exe:0xC00000FD:堆栈溢出的 0x00168a07 处未处理的异常"。

这样调用两个文本文件是错误的吗?下面是我的代码。我正在为QR房主方法生成算法。但是由于我已经在这里失败了,所以我无法继续我的算法。希望知道这里出了什么问题。以下是:

test1.in 矩阵 A:

1.00            -6.00           
34.00           -1644.00            
803.00          -42258.00           
15524.00        -831864.00          
285061.00       -15355806.00       
5153062.00      -278046852.00

test2.in 矩阵 B:

-1875.00      17976.00        485714.00        -501810.00    
5370.00       409584.00      -973084.00        559740.00 
291495.00     9193128.00     -64643018.00      55199850.00    
6351060.00    175638624.00   -1430791544.00    1249618200.00    
120491745.00  3213894936.00  -27252104806.00   23932788870.00     
2200175790.00 58033455312.00 -498213904852.00  438253167540.00 

这是我的代码:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#define M 6
#define N 2
#define x 6
#define y 4
#define MAX 100
using namespace std;
int main()
{
double A[MAX][MAX], B[MAX][MAX];
int i, j;
ifstream ifp;
ifp.open("test1.in", ios::in);
cout << "Matrix A" << setw(40) << endl;
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
ifp >> A[i][j];
cout << setw(20) << A[i][j];
}   
cout << endl;
}
ifp.close();
ifp.open("test2.in", ios::in);
cout << "Matrix B" << setw(40) << endl;
for(i=0;i<x;i++)
{ 
for(j=0;j<y;j++)
{
ifp >> B[i][j];
cout << setw(20) << B[i][j];
} 
cout << endl;
}
ifp.close();
cin.get();
}

我怀疑这是您程序当前设计的问题:引发的异常是堆栈溢出异常,这意味着您的堆栈已满。

发生这种情况是因为您在堆栈上声明了矩阵 A 和 B,并为它们保留了您甚至不需要的巨大空间(可能只是现在(。

所以我认为你有两种可能性:要么减少分配给矩阵的空间,例如。 像这样贴花 A 和 B:

double A[M][N], B[M][N];

或者,您可以在堆上声明AB。为此,我建议您将矩阵的类型从double[][]更改为std::vector< std::vector<double> >,因为向量会自动将其值存储在堆上,您不必手动使用newdelete

#include <vector>
int main()
{
std::vector< std::vector<double> > A, B; // The only modified line !!
int i, j;
ifstream ifp;
ifp.open("test1.in", ios::in);
cout << "Matrix A" << setw(40) << endl;
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
ifp >> A[i][j];
cout << setw(20) << A[i][j];
}   
cout << endl;
}
ifp.close();
ifp.open("test2.in", ios::in);
cout << "Matrix B" << setw(40) << endl;
for(i=0;i<x;i++)
{ 
for(j=0;j<y;j++)
{
ifp >> B[i][j];
cout << setw(20) << B[i][j];
} 
cout << endl;
}
ifp.close();
cin.get();
}

这个小小的修改应该足够:)!