给出以下代码:
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 4; j++)
{
if (col_A[i] == row_B[j])
{
printf("%d %d %2.2f\n",
row_A[i], col_B[j], val_A[i] * val_B[j]);
val_D[i] = val_A[i] * val_B[j];
row_D[i] = row_A[i];
col_D[j] = col_B[j];
}
}
}
具有以下输出:
1 1 3.00
1 2 3.00
1 1 3.00
2 1 3.00
2 2 4.00
3 1 4.00
3 2 4.00
3 1 6.00
row_D = [ 1 1 2 2 3 3 0 0 ]
col_D = [ 1 1 2 2 0 0 0 0 ]
val_D = [ 3.00 3.00 3.00 4.00 4.00 6.00 0.00 0.00 ]
将值正确存储到val_D,row_D和col_D的正确方法是什么? Row_D应包含三元组第一列的值,Col_D应包含第二列的值,而Val_D应包含第三列的值。
谢谢。
答案 0 :(得分:1)
引入一个计数器变量,并仅在有更新时对其进行递增。
counter = 0
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 4; j++)
{
if (col_A[i] == row_B[j])
{
printf("%d %d %2.2f\n",
row_A[i], col_B[j], val_A[i] * val_B[j]);
val_D[counter] = val_A[i] * val_B[j];
row_D[counter] = row_A[i];
col_D[counter] = col_B[j];
counter = counter + 1;
}
}
}