c++ - 不同的IDE输出不同?

标签 c++ ide compilation

我遇到以下问题:我使用 Qt IDE 编写代码。我被告知,当人们尝试使用其他 IDE(如 codeblocks 或 visual studio)编译它时,他们得到的输出是不同的,并且存在错误。任何想法可能是什么原因造成的?我给你举个例子:

这是牛顿法,函数的根是 2.83 左右。每次我在 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

最佳答案

是的,您遇到了未定义的行为:

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 的结果放入返回注册表、共享注册表或其他),但事实是一切皆有可能。一些编译器在后续运行中可能表现相同,一些可能一直崩溃。

关于c++ - 不同的IDE输出不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482932/

相关文章:

c++ - 将模板函数传递给 std::for_each

emacs - 如何让 Emacs 转换模式忽略出现在 virtualenv Cython 项目中的大多数文件?

java - STS(Spring Tool Suite) 和 Eclipse

windows - 将 COBOL 编译为适用于 Windows 的 32 位可执行文件

命令提示符 : class file has wrong version 52. 0 中的 Java 编译错误,应为 50.0

c++ - 为什么将字符串(数组)转换为 char 会导致小写 "c"

java - 从 native 代码分派(dispatch)的 pthread 可以回调到 JNI 吗?

c++ - 为什么 -std=c++98 标志有时不起作用?

javascript - 是否有与浏览器无关的 Javascript IDE?

c++ - 如何编译 C++ 项目(使用 g++)以在其他计算机上使用?