我不明白是什么原因。它应该输出一个矩阵和一个具有您自己设置的维度的向量。请告诉我错误。
// Function for simple initialization of matrix and vector elements
void DummyDataInitialization(double* pMatrix, double* pVector, int Size)
{
int i, j; // Loop variables
for (i = 0; i < Size; i++)
{
pVector[i] = 1;
for (j = 0; j < Size; j++)
pMatrix[i * Size + j] = i;
}
}
// Function for memory allocation and data initialization
void ProcessInitialization(double* &pMatrix, double* &pVector, double*
&pResultVector, int Size) {
// Setting the size of initial matrix and vector
do
{
printf("\nEnter size of the initial objects: ");
scanf("%d", &Size);
printf("\nChosen objects size = %d", Size);
if (Size <= 0)
printf("\nSize of objects must be greater than 0!\n");
}
while (Size <= 0);
// Memory allocation
pMatrix = new double [Size * Size];
pVector = new double [Size];
pResultVector = new double [Size];
// Initialization of matrix and vector elements
DummyDataInitialization(pMatrix, pVector, Size);
}
// Function for formatted matrix output
void PrintMatrix(double* pMatrix, int RowCount, int ColCount)
{
int i, j; // Loop variables
for (i = 0; i < RowCount; i++)
{
for (j = 0; j < ColCount; j++)
printf("%7.4f ", pMatrix[i * ColCount + j]);
printf("\n");
}
}
// Function for formatted vector output
void PrintVector(double* pVector, int Size)
{
int i;
for (i = 0; i < Size; i++)
printf("%7.4f ", pVector[i]);
printf("\n");
}
int main(int argc, char *argv[]) {
double *pMatrix=NULL, *pVector=NULL, *pResultVector=NULL;
int Size=0, RowCount=0, ColCount=0;
// Memory allocation and data initialization
ProcessInitialization(pMatrix, pVector, pResultVector, Size);
PrintMatrix( pMatrix, RowCount, ColCount);
PrintVector(pVector, Size);
// Matrix and vector output
printf("Initial Matrix: \n");
PrintMatrix(pMatrix, Size, Size);
printf("Initial Vector: \n");
PrintVector(pVector, Size);
_getch();
system("pause");
}
观察调试器中的 Size 变量:将它传递给值初始化过程,因此它的新值只存储在过程中,并且在 main() 中它始终为 0(声明时的初始化)。
使用通过引用传递变量。
您的PrintMatrix函数接受三个参数:
根据您的想法,如果我正确理解了代码,ProcessInitialization函数有一个int Size参数,用于存储矩阵的行数/列数。但问题是你传递了一个 Size 变量的副本,当你退出函数时,当然会得到调用函数之前的变量值。您需要更改ProcessInitialization函数的声明和实现,如下所示:
如您所见,我修复了最后一个int Size参数,如下所示:
,通过引用添加传递。结果,在此修复之后,代码开始产生以下结果: