#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;
}
If I write the print statements for mean, num and elements of the array I get the following output:
Average (moy): 2
Elements in X: 0 2 4 6 8
Number of elements greater than the average: 3
This is not an openmp problem , you declared
moyas anintand then to calculate the mean you do:moy += X[i] / N;your
Xarray contains0, 2, 4, 6, 8andN = 5, when the division is performed you are trying to put adoubleinside anintso your sum becomes essentially:0/5 = 0+2/5 = 0+4/5 = 0+6/5 = 1+8/5 = 1=0+0+0+1+1=2you need to either make
moyandXadoubleor, better, to makemoyadouble, sum all the elements insidemoyAND THEN domoy/Nto get the correct result