2013-01-23 113 views
1

我有以下問題:我用Qt IDE編寫我的代碼。我被告知,當人們試圖用其他IDE(如codeblocks或visual studio)編譯它時,他們得到的輸出是不同的,並且存在功能障礙。任何想法可能造成這種情況?我會給你一個例子:不同IDE的不同輸出?

這是牛頓的方法與一個函數誰的根是2.83something。每次我在Qt中運行它時,我都會得到相同的,正確的計算結果。我在代碼塊中獲得了「nan」,在visual studio中也獲得了不相關的東西。我不明白,我的代碼中有沒有出現錯誤?什麼可能導致這種情況?

#include <iostream> 
#include <cmath> // we need the abs() function for this program 

using namespace std; 

const double EPS = 1e-10; // the "small enough" constant. global variable, because it is good programming style 

double newton_theorem(double x) 
{ 
    double old_x = x; // asign the value of the previous iteration 
    double f_x1 = old_x*old_x - 8; // create the top side of the f(x[n+1] equation 
    double f_x2 = 2 * old_x; // create the bottom side 
    double new_x = old_x - f_x1/f_x2; // calculate f(x[n+1]) 
    //cout << new_x << endl; // remove the // from this line to see the result after each iteration 
    if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer; 
    { 
     return new_x; 
    } 
    else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X; 
    { 
     newton_theorem(new_x); 
    } 
}// newton_theorem 

int main() 
{ 
    cout << "This program will find the root of the function f(x) = x * x - 8" << endl; 
    cout << "Please enter the value of X : "; 
    double x; 
    cin >> x; 
    double root = newton_theorem(x); 
    cout << "The approximate root of the function is: " << root << endl; 

    return 0; 
}//main 

回答

3

是的,你碰上未定義行爲

if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer; 
{ 
    return new_x; 
} 
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X; 
{ 
    /*return*/ newton_theorem(new_x); // <<--- HERE! 
} 

else分支缺少return

我們可以嘗試解釋爲什麼Qt的工作(其編譯器會自動在返回註冊表把結果newton_theorem,或股份登記處,或其他),但問題的事實是任何事情都可能發生。有些編譯器在後續運行中可能表現相同,有些可能會一直崩潰。

+0

嚴...... UB?那是什麼 ? – Bloodcount

+0

未定義的行爲 – Alex

+0

@Bloodcount編輯。 –