可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to do matrix multiplication using for loops and I am getting an error, "Array Subscript is not an integer" Could I get some help please.
#include <stdio.h> #include <stdlib.h> int main(void) { float Matrix_1[3][3] = {{3.4, 4.4, 1.2},{5.3, 5.7, 2.2},{6.2, -2.4, 0.9}}; float Matrix_2[3][3] = {{7.3, 4.9, 3.7},{-2.4, 4.9, -10.2},{7.3, 5.2, 1.7}}; float i, j, k; float result[3][3]; for (i = 0; i < 1; i++) { for (j = 0; j < 3; j++) { for(k = 0; k < 3; k++) { result = result + Matrix_1[i][k] * Matrix_2[k][j]; } } } printf("The result of multiplying the matrices together\n"); printf("%.3f\t%.3f\t%.3f\n",result[0][0],result[0][1],result[0][2]); printf("%.3f\t%.3f\t%.3f\n",result[1][0],result[1][1],result[1][2]); printf("%.3f\t%.3f\t%.3f\n",result[2][0],result[2][1],result[2][2]); system("PAUSE"); return 0; }
回答1:
The subscripts, or array indices need to be an int
value. Therefore, change this:
float i, j, k;
to this: int i, j, k;
Also, you have declared result
as a 3X3 matrix. So, when storing data into the matrix, you have to store element - by - element. So, instead of this:
result = result + Matrix_1[i][k] * Matrix_2[k][j];
change it to this: result[i][j] = result[i][j] + Matrix_1[i][k] * Matrix_2[k][j];
One more thing: Initialise the result
matrix!! In the above statement, you are using the value of its elements in the matrix, which maybe holding some garbage value, and you may not get the desired result. So, before using the result
matrix, initialise it.
A simple way:
for(i=0;i<3;i++) { for(j=0;j<3;j++) result[i][j]=0; }
One last thing: your outermost for loop
runs only one time: for (i = 0; i < 1; i++)
Probably you wanted this: for (i = 0; i < 3; i++)
Finally, the modified code: http://ideone.com/26GSJa
回答2:
float i, j, k;
have to be:
int i, j, k;
(or any other integer types) as you can only use integer values for array indexes.
result = result + Matrix_1[i][k] * Matrix_2[k][j]; ^ ^ have to be integers