2013-07-11 33 views

回答

7

要擴大@TheOtherGuy的答案,可以在發生溢出時取消操作。

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

int main(void) 
{ 
    double param, result; 

    errno = 0; 
    param = 1e3; 
    result = exp (param); 
    if (errno == ERANGE) { 
     printf("exp(%f) overflows\n", param); 
     result = param; 
    } 
    printf ("The exponential value of %f is %f.\n", param, result); 
    return 0; 
} 
+1

我認爲你錯了,要創建一個符合程序,你需要在產生溢出之前測試溢出。看看這個http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-cc – WildThing

+0

@ user2114690好的鏈接,謝謝 –

+1

添加到@詹姆斯Kanze說,我認爲我錯了。你的解決方案是正確的謝謝 – WildThing

12
#include <errno.h> 

當oferflow發生時,然後錯誤號設置爲ERANGE


下一次,提問前最好做好功課。

谷歌搜索:「C++ EXP」返回本作的第一個結果http://www.cplusplus.com/reference/cmath/exp/
在頁面的中間,有你在尋找什麼。

+0

目的是檢查溢出發生之前。否則,會產生未定義的行爲。 – WildThing

+2

比您想象的要容易。只要嘗試,如果errno設置爲ERANGE再次嘗試不同的值。這種方法是*簡單*,*便宜*,然而*有效*。 –

+0

這是一個溢出後測試,不適用於我的問題,因爲輸入每次都有所不同。我想在它發生之前檢查可能的溢出 – WildThing

1

預先檢查溢出的最佳方法是在個案基礎上智能地執行此操作。

使用您的對數和指數的知識,你應該能夠識別相似INT_MAX使用性質潛在溢出:檢查這些C++ Limitations

我一起扔了一個粗略的樣本C++執行,假設你事先知道你正在嘗試什麼限制跟隨。

#include <iostream> 

// nTh root calculator 
bool is_exp_overflow(int input_val, int exponent) 
{ 
    my_max = pow(INT_MAX, (1/exponent); 
    if (input_val > my_max) 
    { 
     return true; 
    } 
    else 
     return false; 
} 

void runExp(int my_input, int my_exp) 
{ 
    // Do maths 
} 

int main() 
{ 
    int my_input = 0; 
    int my_exp = 0; 
    std::cout << "Enter test value\n"; 
    std::cin >> my_input; 
    std::cout << "Enter test exponent\n"; 
    std::cin >> my_exp; 
    bool exp_unsafe = 1; 
    exp_unsafe = is_exp_overflow(my_input, my_exp); 

    if (!exp_unsafe) 
     runExp(my_input, my_exp); 
    else 
     std::cout << "Code is unsafe\n"; 

    return 0; 
} 

如果你正在尋找捕捉錯誤驗屍,檢查errno in range

2

對於EXP()處理:

只是比較反對您指定登錄一個變量(FLT_MAX)。 FLT_MAX是最大的浮動。 您可以在之前做計算exp()。因爲log()exp()的倒數

#include <iostream> 
#include <math.h> 
using namespace std; 

int main() 
{ 
    float a=1E+37f; // an example of maximum finite representable floating-point number. 
    //max value can change with platform so, 
    //either use definitions or use a function you wrote 
    // a= getMaxFloat(); or a=FLT_MAX 
    float b=log(a); // limit of float to give in exp(); 
    float c=3242325445.0f; // test variable 
    cout << "Hello world!" << endl; 
    if(c>b){cout<<"you should not take exp of "<<c<<endl;}else{cout<<"go on"<<endl;} 

    return 0; 
} 

對於日誌()處理:

1)你不能溢出X之前everflow日誌(X)。 (對於上限)

2)對於log(x),Float's/Double's(x)精度不足以溢出到負無窮大。

3)確保x大於零。

+1

你從哪裏得到你最大的浮動?它依賴於平臺,並且有爲任何平臺獲取它的手段。 – juanchopanza

+0

然後在計算之前檢查溢出之前,他應該檢查他的平臺的限制。 –

+0

你應該建議,在你的答案,而不是引用一些奇怪的數字,並聲稱它是最大的浮點數:) – juanchopanza

1

不是阻止更好,你可以捕獲該異常:

try { 
    z=exp(n); 
} catch (...) { 
    puts("Can't calcute exp..."); 
} 
+0

...在c + +。在c中沒有例外。 – urzeit

+2

'exp'確實沒有**在溢出時拋出異常。有一個**浮點異常**,但這是浮點特有的「異常」的不同含義。它與C++異常無關 –