gpt4 book ai didi

c - C 中的矩阵乘法问题

转载 作者:行者123 更新时间:2023-11-30 21:31:34 26 4
gpt4 key购买 nike

我正在用 C 语言制作一个矩阵乘法计算器。当我运行它时,会输出许多数字和结果:

57736 segmentation fault

我哪里写错了?这是我写的代码:

int Mtx1row, Mtx1col, Mtx2row, Mtx2col, c, d, e;
int first[10][10], second[10][10], mult[10][10];

获取第一个矩阵行和列

  printf("First Matrix: # of row and col?\n");
scanf("%d%d", &Mtx1row, &Mtx1col);

获取第二个矩阵的行和列

  printf("Second Matrix: # of row and col?\n");
scanf("%d%d", &Mtx2row, &Mtx2col);

比较第一个矩阵列与第二个矩阵行

  if (Mtx1col != Mtx2row){
printf("Mtx1col != Mtx2row (x _ x)\n");
return 1;
}

获取第一个矩阵的元素

  printf("Enter elements of First Matrix: \n");
for (c = 0; c < Mtx1row; c++)
for (d = 0; d < Mtx1col; d++)
{
printf("\tEnter element %d%d: ", c+1, d+1);
scanf("%d", &first[c][d]);
}

获取第二个矩阵的元素

printf("Enter elements of Second Matrix: \n");
for (c = 0; c < Mtx2row; c++)
for (d = 0; d < Mtx2col; d++)
{
printf("\tEnter element %d%d: ", c+1, d+1);
scanf("%d", &second[c][d]);
}

将矩阵 1 和 2 相乘并存储到矩阵乘积

  for (c=0; c < Mtx2row; c++){
for (d=0; d < Mtx2col; d++){
for (e=0; e < Mtx1col; e++){
mult[c][d] += first[c][d] * second[d][e];
}
}
}

最佳答案

两个矩阵可以相乘,只要一个条件

#columns of the first matrix = #rows of the second matrix.

因此,您需要在创建 2D 数组本身之前检查这一点。

if(Mtx1col == Mtx2row){
//proceed creating the matrices
int first[Mtx1row][Mtx1col], second[Mtx2row][Mtx2col];
int mult[Mtx1row][Mtx2col]; // The resulting matrix is Mtx1row * Mtx2col
// You have variable length arrays(VLAs) above.
}
else{
// put the f/b code here
}

注意

Under C11, VLAs are an optional feature rather than a mandatory feature, as they were under C99.
The term variable in variable-length array does not mean that you can modify the length of the array after you create it. Once created, a VLA keeps the same size. What the term variable does mean is that you can use a variable when specifying the array dimensions when first creating the array.

<小时/>

以上摘录自Stephen Prata 的 C++ Primer Plus 第 6 版

关于c - C 中的矩阵乘法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com