矩阵自乘(C语言编程)

来源:百度知道 编辑:UC知道 时间:2024/06/24 07:14:51
输入:
输入有多组数据。矩阵的阶数 n(1 < n < 20 ) ,并且矩阵内的元素大于0 小于50 。接下去是n行,n列。n = 0 时退出。

输出:
自乘后得到的新矩阵,并带一个空行。

sample:

input:

2
1 1
2 2
output:
3 3
6 6

请问:如何输入自定义阶数的矩阵?我基础不好,写了下面的输入程序,
只知道int a[n][n]不对。
#include<stdio.h>
void main()
{
int n,i,j;
int a[n][n];
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j] = rand()%50;
scanf("%d",&a[i][j]);
}

1定义数组 a[n][m]的数值不能是变量
可以用宏/常量/指针申请空间

2for 循环注意被循环的部分要加上{ }

如果编译器支持C99标准,有动态数组,C++也有动态数组的概念,可是大部分C编译器现在还只能动态申请内存实现你的想法:e.g. :实现pScore[m][n]
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *pScore = NULL, i, j, m, n;

printf("Please enter array size m,n:");
scanf("%d,%d", &m, &n); //输入m和n,你的例子里可取m=n

//申请m*n个sizeof(int)字节的存储空间
pScore = (int *) calloc(m*n, sizeof(int));
if (pScore == NULL)
{
printf("No enough memory!\n");
exit(0);
}

printf("Please enter the number:\n");
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
{
scanf("%d",&pScore[i*n+j]); //输入
}
}

{//其他函数;}

free(pScore);
}