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
嚴...... UB?那是什麼 ? – Bloodcount
未定義的行爲 – Alex
@Bloodcount編輯。 –