我有以下问题:我用Qt IDE编写代码。我被告知,当人们尝试使用其他IDE(如codeblocks或visual studio)编译它时,他们获得的输出是不同的,并且存在功能。有什么想法可以导致这个?我会举个例子:
这是Newton的方法,其函数的根是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
答案 0 :(得分: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!
}
return
分支上缺少else
。
我们可以尝试解释为什么Qt有效(它的编译器自动将newton_theorem
的结果放在返回注册表中,或者共享注册表,或者其他),但事实是任何事情都可能发生即可。有些编译器在后续运行中的行为可能相同,有些可能会一直崩溃。