奇怪的浮点异常

时间:2015-11-17 00:59:47

标签: exception sigfpe

在下面的代码片段中,我在运行时遇到浮点异常。我相信异常发生在正在进行除法的行。当我评论该行时,我没有得到任何错误。

当我使用“-g”标志在gcc中编译时(尝试调试)或者如果我在“if语句”之后立即插入一些“cout语句”,那么我也没有得到任何浮动点运行时异常。

我已经在这个代码上盯着我的屏幕好几个小时,也许我犯了一些愚蠢的错误..请帮忙!

    double prev;
    for(int i=0;i<320;i++)
    for(int j=0;j<320;j++) 
    {
        double x = -8 + i*0.05;
        double y = -8 + j*0.05;
        r= sqrt(x*x+y*y);

        double kappa = atanh(  (2*r)  / ( 2 +  r*r)  );                     

        if( fabs(r) > 1e-7 )
        { 
            prev= ( x*sinh(kappa) )/r; 
        }
         else
        {
            prev=0;         

        }
        /* more stuff */ 
    }

更新: 所以我能够通过在争议线上的分母上添加1e-15来解决问题。

prev= ( x*sinh(kappa) )/(r+1e-15);

当r = 0时,我仍然不确定为什么if条件给出了if(fabs(r)&gt; 1e-7);

1 个答案:

答案 0 :(得分:0)

一个负数的Sqrt?试试

#include <iostream>
#include <string>

using namespace std;

int main() {
  string name;
  int FavNum;
  cout << "Hello Sir what is your name" << endl;
  cin >> name >> "\n";

  cout << "Well Hello " << name
       << "What is your Favorite number between 1 and 100" << endl;
  cin >> name >> "\n";
  if (FavNum > 100) {
    cout << "Wow you like big numbers, but sorry you cant use that one" << endl;
  } else if (FavNum >= 90) {
    cout << "Wow you like huge numbers!" << endl;
  } else if (FavNum <= 10) {
    cout << "Wow you like smaller numbers!!!" << endl;
  } else if (FavNum == 13) {
    cout << "Wow your favorite number is the most unluckiest number in the "
            "whole entire universe and I don't know many people that would "
            "choose this number I'm proud comrad"
         << endl;
  } else if (FavNum <= 89) {
    cout << "You have a very nice number thats average try again!" << endl;
  }
}

在您的代码段的第7行。