#include<iostream>
#include<cmath>
using namespace std;
int f(float x)
{
float y;
y=x*x+3*x-4;
return y;
}
int df(float x)
{
float y;
y=2*x+3;
return y;
}
int main()
{
float x1,x0;
x1=0;
do
{
x0=x1;
x1=x0-f(x0)/df(x0);
}while(fabs(x1)>=0.00001);
cout<<"x="<<x1<<endl;
return 0;
}
这段代码运行后没有输出,为什么啊?
算法有问题
#include <cmath>
#include <iostream>
auto f(float x) -> float
{
float y;
y = x * x + 4 * x + 4;
return y;
}
auto df(float x) -> float
{
float y;
y = 2 * x + 2;
return y;
}
int main()
{
float x1;
float x0;
x1 = 0;
do
{
x0 = x1;
x1 = x0 - f(x0) / df(x0);
} while (fabs(x1 - x0) >= 0.00001);
std::cout << "x=" << x1 << std::endl;
return 0;
}
因为函数的返回值类型是int ,由于截取导致 fabs(x1)>=0.00001一直成立,while会无限循环