这是我的矩阵乘法代码,但是当我运行它时,我得到第一行的正确结果,但第二行和第三行的结果错误(主要是大的负数)。这是我的第一个程序,所以我使用了一些我在网上找到的代码
#include <iostream>
__global__ void MnozenjeMatrica(int* d_c, int* d_a, int* d_b)
{
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
int d = 0;
for(int i=0; i<3; i++)
{
int x = d_a[row * 3 + i];
int y = d_b[i * 3 + col];
d += x * y;
}
d_c[row * 3 + col] = d;
}
int main()
{
const int SIZE = 9 * sizeof(int);
int a[3][3] = {{2, 4, 6}, {1, 3, 5}, {8, 4, 1}};
int b[3][3] = {{5, 8, 34}, {5, 7, 5}, {1, 4, 31}};
int c[3][3] = {{5, 8, 34}, {5, 7, 5}, {1, 4, 31}};
int* d_a;
int* d_b;
int* d_c;
cudaMalloc((void**) &d_a, SIZE);
cudaMalloc((void**) &d_b, SIZE);
cudaMalloc((void**) &d_c, SIZE);
cudaMemcpy(d_a, a, SIZE, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, b, SIZE, cudaMemcpyHostToDevice);
MnozenjeMatrica<<<3, 3>>>(d_c, d_a, d_b);
cudaMemcpy(c, d_c, SIZE, cudaMemcpyDeviceToHost);
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
printf("%d\t", c[i][j]);
}
printf("\n");
}
}