如何在if语句被满足后得到数组的最后一个值

how to get the last value of array after the if statement have been satisfied

本文关键字:数组 最后一个 满足 if 语句      更新时间:2023-10-16

这是我目前所做的。我的问题是迭代函数返回数组的第一个值。我希望它返回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
}