如何在if语句被满足后得到数组的最后一个值
how to get the last value of array after the if statement have been satisfied
这是我目前所做的。我的问题是迭代函数返回数组的第一个值。我希望它返回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;
}
您可以将想要返回的内容保存在本地变量中。
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
}
相关文章:
- 在c++中为double类型的数组创建一个unique_ptr
- 从数组构造一个跨度<shared_ptr<T>><shared_ptr<void>>
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 如何将 v8::FunctionCallbackInfo<v8::Value> 数组从一个隔离复制到另一个隔离?
- 我怎么能有一个以2D数组为参数的函数,而数组有一个我想更改的参数/维度
- 为什么我的数组输出一个不在其中的元素
- 查找数组最后 3 个数字的平均值
- 数组 - 最后一个索引
- 将数组作为一个参数从一个函数传递到C 中的另一个函数
- 从字符串数组创建一个字符数组
- 如何在C 中的小写中将文本从数组的一个维度传递到另一个维度
- 在对结构数组的一个成员进行排序后,移动其成员的其余部分
- 为什么数组在一个文件中打印,但在发送到另一个文件时却缺少数字
- C++,为什么多维数组的一个元素的增加似乎增加了另一个元素
- 将数组的一个元素与整个数组元素进行比较
- 如何将数组从一个函数传递到另一个函数
- C++:通过引用传递对象数组(指向一个?的指针)
- 查找最大和连续子数组-另一个版本
- 如何使用一个整数数组作为一个无序映射的键
- 使用for循环将char数组的一个元素复制到另一个元素