提问人:M V 提问时间:10/11/2023 更新时间:10/11/2023 访问量:52
为什么在使用 openMP 计算数组的平均值时得到错误的结果?
Why do I get the wrong results while calculating the mean of the array using openMP?
问:
#include <stdio.h>
#include <omp.h>
#define N 5
int X[N];
int main() {
int num = 0;
int moy = 0;
// Initialize the array (you should populate it as needed)
for (int i = 0; i < N; i++) {
X[i] = i * 2; // Example initialization
}
// Calculate the average
#pragma omp parallel for reduction(+:moy)
for (int i = 0; i < N; i++) {
moy += X[i] / N;
}
// Count elements greater than the average
#pragma omp parallel for reduction(+:num)
for (int i = 0; i < N; i++) {
if (X[i] > moy) {
num++;
}
}
printf("%d\n", num);
return 0;
}
如果我为数组的 mean、num 和元素编写 print 语句,我会得到以下输出: 平均 (moy): 2 X 中的元素:0 2
4 6 8 大于平均值的元素
数:
3
答:
2赞
John Doe
10/11/2023
#1
这不是一个openmp问题,你声明为一个,然后计算你做的平均值:moy
int
moy += X[i] / N;
你的数组包含 和 ,当执行除法时,你试图把一个放在 里面,所以你的总和基本上变为:X
0, 2, 4, 6, 8
N = 5
double
int
0/5 = 0
+
2/5 = 0
+
4/5 = 0
+
6/5 = 1
+
8/5 = 1
= 0+0+0+1+1
= 2
你需要要么做一个,要么更好的是,做一个,把里面的所有元素相加,然后做得到正确的结果moy
X
double
moy
double
moy
moy/N
评论