【问题标题】:" Floating point exception (core dumped) "“ 浮点异常(核心转储)”
【发布时间】:2021-11-17 05:14:24
【问题描述】:

大家好,我正在尝试使用C++parallel 中编写梯形规则,它编译时没有错误,但是当我运行它时会给出“浮点异常(核心转储)” parallels@parallels-Parallels-Virtual-Platform:~/Desktop$ g++ -Wall assignmentmemt.cpp -o output -lpthread parallels@parallels-Parallels-Virtual-Platform:~/Desktop$ ./output 用法:./输出 n 是项数,应 >= 1 parallels@parallels-Parallels-Virtual-Platform:~/Desktop$ ./output 3 5 浮点异常(核心转储) parallels@parallels-Parallels-Virtual-Platform:~/Desktop$ ^C parallels@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 >= 1\n");
   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;
} 

【问题讨论】:

  • 除以零可能吗?你的调试器说什么?
  • 使用调试器找出错误发生在哪一行。
  • 一如既往:在调试器中运行它。该工具会在问题出现时为您停止程序。
  • stepSize = (1 - 0)/subInterval; 是整数除法。所以1除以1以外的任何数字将是0
  • 请注意,整数除以 0 会导致浮点异常。这只是 C 实现者的恶作剧。

标签: c++ multithreading


【解决方案1】:

浮点异常:核心转储 - 几乎 100% 的时间都被零除。我想我从来没有因为任何其他原因打过这个。

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多