gpt4 book ai didi

c - C OpenMP 并行程序中的奇怪错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:33 24 4
gpt4 key购买 nike

我正在研究并行编程的模式。我正在浏览书中的示例,但有一个示例无法编译。这是代码:

#include <stdio.h>
#include <math.h>
#include <omp.h>

int main() {

int i;
int num_steps = 1000000;
double x, pi, step, num = 0.0;

step = 1.0/(double) num_steps;

#pragma omp parallel for private(x) reduction(+:sum)
for(i=0; i < num_steps; i++) {
x = (i+0.5) * step;
sum+= 4.0/(1.0+x*x);
}

pi = step *sum;
printf("pi %lf\n", pi);
return 0;
}

enter image description here

我是 PP 的新手,所以我不知道我做错了什么。

最佳答案

代码中没有为 sum 声明变量,因此当编译器到达该行时:

#pragma omp parallel for private(x) reduction(+:sum)

它不知道 sum 是什么,并给出您遇到的编译错误。

要解决此问题,您需要先声明 sum 变量:

double sum = 0.0;
#pragma omp parallel for private(x) reduction(+:sum)

正如评论中所指出的,问题是拼写错误造成的:

double x, pi, step, num = 0.0; //num should be sum here

通过使用 gcc 的所有警告 -Wall 编译器选项进行编译,您将收到有关未使用的变量 num 的警告,这将很快指出问题的根源.

关于c - C OpenMP 并行程序中的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31274898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com