问题陈述如下所示:使用单独的线程来计算每一行的总和,计算二维矩阵中元素的总和。主线程将这些和加起来打印出最终结果。
从目前为止我所看到的,代码可以正确运行。唯一的问题是,当我选择的行数小于列数时(例如,行= 2,列= 3),因为它只计算前两列的总和,而完全忽略了第三列。
这是我用C语言编写的代码,对于理解我做错了或错过的事情的任何帮助,我将不胜感激。谢谢你。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define M 10
#define N 10
int rows, columns, a[M][N], s[M];
// compute the sum of each row
void* f(void* p) {
int k = *((int*) p);
int i;
for (i = 0; i < columns; i++) {
s[i] += a[k][i];
}
return NULL;
}
int main() {
int i, j, *p, rc;
int sum = 0;
pthread_t th[M];
// matrix creation
printf("no. of rows = ");
scanf("%d", &rows);
printf("no. of columns = ");
scanf("%d", &columns);
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
printf("a[%d][%d] = \n", i, j);
scanf("%d", &a[i][j]);
}
}
printf("\nThe matrix is: \n");
for(i=0; i < rows; i++) {
for(j=0; j < columns; j++)
printf("%d ", a[i][j]);
printf("\n");
}
// thread creation
for (i=0; i < rows; i++) {
p = malloc(sizeof(int));
*p = i;
rc = pthread_create(&th[i], NULL, f, p);
if (rc != 0) {
printf("Thread creation failed");
exit(-1);
}
}
for (i=0; i < rows; i++) {
pthread_join(th[i], NULL);
}
// compute the final sum
for (i=0; i < rows; i++) {
sum += s[i];
}
printf("The sum is = %d\n", sum);
return 0;
}
你需要
s[k] += a[k][i];
代替
s[i] += a[k][i];
各行的总和应在每个各指标加起来row
为s
被声明为s[M]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句