大家好,我在试着写梯形规则在
parallel
使用C++
它编译没有错误,但当我运行它给出"浮点异常(核心转储)"parallels@parallels-Parallels-Virtual-Platform:~/Desktop$ g++ -Wall assignment .cpp -o output -lpthreadparallels@parallels-Parallels-Virtual-Platform: ~/桌面。美元/输出用法:输出N是项的个数,应该是>= 1parallels@parallels-Parallels-Virtual-Platform:~/Desktop$ ./output 3浮点异常(核心转储)parallels@parallels-Parallels-Virtual-Platform: ~/Desktop $ ^ Cparallels@parallels-Parallels-Virtual-Platform: ~/Desktop $
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
const int MAX_THREADS = 1024;
long thread_count;
long long n;
double sum;
pthread_mutex_t mutex;
#define f(x) 1/(1+pow(x,2))
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads> <n> n", prog_name);
fprintf(stderr, " n is the number of terms and should be >= 1n");
exit(0);
}
void Get_args(int argc, char* argv[]) {
if (argc != 3) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]);
n = strtoll(argv[2], NULL, 10);
if (n <= 0) Usage(argv[0]);
}
void* Trapezoidal_Rule(void* rank) {
long long integration=0 , stepSize, k;
long subInterval = (long) rank;
int i;
stepSize = (1 - 0)/subInterval;
integration = f(0) + f(1);
for(i=1; i<= subInterval-1; i++)
{
k = 0 + i*stepSize;
integration = integration + 2 * (f(k));
}
pthread_mutex_lock(&mutex);
integration = integration * stepSize/2;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
Get_args(argc, argv);
thread_handles = (pthread_t *) malloc(thread_count*sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], NULL, Trapezoidal_Rule, (void*)thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], NULL);
printf(" integration is = %.15f n", sum);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
浮点异常:core转储——几乎100%的情况下它会被零除。我想我从来没有因为任何其他原因击中过这个。