gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:57:35 25 4
gpt4 key购买 nike

我遇到以下问题:我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com