Program help

Have your program find which of the y values is closest to 10 (either larger or smaller).
have the program print the x value that gives this closest y value. Also, print how close
the y value is to 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cmath>


using namespace std;

int main ()

{
    float x, y;

    cout<<"\t\t\tOutput of First Program!"<<endl<<endl;
    cout<<"\t\t\t\tValue of X:\t\tValue of Y:"<<endl;
    for (x=-3; x<=4; x+=0.5)
    {
        y=(9*x*x*x-27*x*x-4*x+12)/(sqrt(3*x*x+1) + abs(5-x*x*x*x));

        if(y==0)
            cout<<"Y is Zero ";
        if(y>0)
            cout<<"Y is Positive ";
        if(y<0)
            cout<<"Y is Negative ";
            cout<<"\t\t\tX= "<<x<<"\t\t\tY= " <<y<<endl;
        if(x==4)
            cout<<endl<<endl<<"The program is halting";



    }

    return 0;
}


How do I go about doing these? Could you please give me a hint but not give me the answer. Thanks for help.
Last edited on
So, you have an equation 10 = f(x) for which you don't have analytic solution.

You have to make a guess; pick some value of x. Calculate f(x). If it is not spot on, then pick a new x and repeat. The question is, how to pick the x wisely so that you do get closer to the correct answer? There are plenty of algorithms for that.
You could have two variables that hold x and y values separate from the ones in your loop and test those. Something like . . .
1
2
3
4
5
6
7
8
float closestY = y;
float closestX = x;

if(/*y is closer to 10 than closestY*/)
{
    closestY = y;
    closestX = x;
}
Last edited on
Topic archived. No new replies allowed.