#pragma omp parallel for要求循环变量是一个整数。那么如果循环变量不是整数,会发生什么呢?如本例所示?
#include <stdio.h>
#include <math.h>
#define START (M_PI/2)
#define END (M_PI*2)
double f(double x)
{ return sin(x/2)+1;
}
int main(int argc, char *argv[])
{ double total = 0, x;
int partitions;
double slice;
printf("How many partitions? "); fflush(stdout);
scanf("%d", &partitions);
slice = (END-START)/partitions;
for (x = START + (slice/2); x < END; x = x + slice)
total = total + f(x);
total = total * slice;
printf("The integration is %1.20f\n", total);
}
如何将此程序转换为OpenMP? 感谢
答案 0 :(得分:1)
首先,您应该对代码的样式更加小心,尤其是缩进。代码如
for (x = START + (slice/2); x < END; x = x + slice)
total = total + f(x);
total = total * slice;
可能会产生误导,并且在将其写成
时会让您的生活更轻松for (x = START + (slice/2); x < END; x = x + slice) {
total = total + f(x);
}
total = total * slice;
代替。
关于你的问题,正如安德鲁所提到的,你可以通过用整数变量循环遍历分区来完全避免它,即
#pragma omp parallel for private(x) reduction(+:total)
for(int i = 0; i < partitions; i++) {
x = START + slice/2 + i*slice;
total = total + f(x);
}
total = total * slice;