1

我有以下问题:我用 Qt IDE 编写代码。我被告知,当人们尝试使用其他 IDE(如代码块或 Visual Studio)编译它时,他们得到的输出是不同的,并且存在 maufunctions。有什么想法会导致这种情况吗?我给你举个例子:

这是牛顿法,其函数的根为 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
4

1 回答 1

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放入返回注册表,或共享注册表,或其他任何东西),但事实是任何事情都可能发生。一些编译器在随后的运行中可能表现相同,一些可能会一直崩溃。

于 2013-01-23T15:14:58.783 回答