这是我到目前为止所拥有的。我的问题是迭代函数返回数组的第一个值。我希望它在if语句满足后返回最后一个值。
求解方程式# include <iostream>
using namespace std;
double iteration(double u, double l);
double f (double x);
inline bool closerlimit(double u, double l);
double e;
void main()
{
cout << "Enter the upper Limit: " <<endl;
double ul;
cin >> ul;
cout << "Enter The lower Limit: " <<endl;
double ll;
cin >> ll;
cout<<"enter level of error: "<<endl;
cin>>e;
double r;
r=iteration(ul,ll);
cout<<"root is : "<< r<<endl;
}
double f(double x)
{
return exp(x)+5*x;
}
// Evaluating the closer limit to the root
// to make sure that the closer limit is the
// one that moves and the other one is fixed
inline bool closerlimit(double u, double l)
{
return fabs(f(u)) > fabs(f(l));
}
这是我的迭代功能。它只返回数组的第一个值。我想要它,以便在满足if语句后,此函数将返回根数组的最新值。
double iteration(double u, double l)
{
double root[100], re=0;
for (int i=0; i<=20; i++)
{
{
root[i] = u - ((f(u)*(l-u)) / (f(l)-f(u)));
if (closerlimit(u,l))
l = root[i];
else
u = root[i];
double re=0;
re=abs((root[i]-root[i-1])/root[i])*100;
if (re<=e) {break;}
}
cout<<"r = "<<root[i]<<endl;
cout<<"re = "<<re<<endl;
return (root[i]);
}
return 0;
}
答案 0 :(得分:1)
您始终可以在本地变量中保存要返回的内容。
double iteration(double u, double l)
{
double root[100], re=0;
double ret = 0.0; //added
int i; // you'll want to use i in cout
for (i=0; i<=20; i++)
{
{root[i] = u - ((f(u)*(l-u)) / (f(l)-f(u)));
if (closerlimit(u,l))
l = root[i];
else
u = root[i];
double re=0;
re=abs((root[i]-root[i-1])/root[i])*100;
if (re<=e) {
ret=root[i]; // save the value;
break;
}
}
cout<<"r = "<<root[i]<<endl; // well, when break is not met, this is uninitialized value
cout<<"re = "<<re<<endl;
return ret; // defaulted to 0
}