我试图让我的程序识别用户输入的稀疏矩阵的每一列中有多少个 1。我想过使用嵌套的 for 循环、if(p[i][j]=1) 和计数器 k++,但它打印大量随机数然后崩溃。我的整个代码都包含在内,但我遇到问题的部分是 int **printColumnStatisticsOfMatrix(int **p)
#include <stdio.h>
#include <stdlib.h>
int **getBinarySparseMatrixFromUser();
int **printColumnStatisticsOfMatrix(int **p);
int main()
{
int **p;
p = getBinarySparseMatrixFromUser();
printColumnStatisticsOfMatrix(p);
return 0;
}
int ** getBinarySparseMatrixFromUser()
{
int atoi(const char *str);
int i;
int j;
int r, c, f, g;
int **p;
char str[20];
char term;
printf("Please enter the number of rows:\n");
scanf("%s", &str);
while(atoi(str)==0)
{
printf("Invalid entry. \nPlease enter the number of rows:\n");
scanf("%s",str);
}
r = atoi(str);
printf("Please enter the number of columns:\n");
scanf("%s", &str);
while(atoi(str)==0)
{
printf("Invalid entry. \nPlease enter the number of columns:\n");
scanf("%s",str);
}
c = atoi(str);
p= malloc(r* sizeof(int*));
for (i=0; i<r; i++)
{
p[i]= malloc(c* sizeof(int));
}
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
p[i][j]=0;
}
}
for (i=0; i<r; i++)
{
printf("Please enter the number of 1's in row %d :\n", (i+1));
scanf("%d", &f);
if (f>0)
{
printf("Please enter column location of the 1's in row %d : \n", (i+1));
for (j=0; j<f; j++)
{
scanf("%d", &g);
p[i][g-1]= 1;
}
}
}
printf("\nYou Have entered the Matrix!!!\n\nI mean this is the Matrix you have entered:\n\n");
return p;
}
<小时/>
(以上所有内容只是为了帮助找到任何可以提供帮助的人,这就是我遇到麻烦的地方)
int **printColumnStatisticsOfMatrix(int **p)
{
int i;
int j;
int c, r, k;
for(i=0; i<r; i++)
{
printf("\t");
for(j=0; j<c; j++)
{
printf("%d ", p[i][j]);
}
printf("\n");
}
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
if(p[i][j]==1)
{
printf("The number of 1’s in column %d is %d\n", (i+1), k);
k++;
}
}
}
}
<小时/>
如果我删除下面所示的部分,它就可以工作,但我仍然需要识别每列中的 1。我知道问题就在这里,但我不明白为什么它会崩溃或为什么它不起作用。
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
if(p[i][j]==1)
{
printf("The number of 1’s in column %d is %d\n", (i+1), k);
k++;
}
}
}
最佳答案
您需要在 main()
中声明 r
和 c
并将它们传递给其他函数。一次通过引用,一次通过值:
int main()
{
int **p;
int r, c;
p = getBinarySparseMatrixFromUser(&r, &c);
printColumnStatisticsOfMatrix(p, r, c);
return 0;
}
int ** getBinarySparseMatrixFromUser(int *r, int *c)
{
// int r, c; <- Remove
...
}
由于您现在将 r
和 c
作为指针传递,因此您必须使用指针表示法来尊重它们:
*r = atoi(str);
然后...
void printColumnStatisticsOfMatrix(int **p, int r, int c)
{
// int r, c; <- Remove
...
}
最后,您想要查找每列中 1 的数量。
// Reverse your indices (and use better variable names)
for (int column = 0; column < c; column++)
{
k = 0;
for (int row = 0; row < r; row++)
{
if (p[row][column] == 1)
k++;
}
// This goes here
printf("The number of 1’s in column %d is %d\n", (column + 1), k);
}
关于c - 识别稀疏矩阵数组 C 的列中的 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33851331/