CIN help

Hi, i am new into coding.

I am creating a program to find the intresection berween two functions.
The program already works but i gave to insert the functions mannualy.

In the example the function is "x * 2 - 3.4" I want to read it with a CIN or something like that.


If somenone has some idea i will apreciate.


float funcao2 (float x)
{
double y = x * 2 - 3.4;

return y;
}
[/code]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

double funcao(const double);

int main()
{
    double x = 0;
    
    cout << "Enter x: ";
    cin >> x;
    
    double y = funcao(x);
    cout << "y = " << y << " for x = " << x << '\n';
    
    return 0;
}

double funcao(const double x)
{
    return x * 2 - 3.4;
}


Enter x: 12.3
y = 21.2 for x = 12.3
Program ended with exit code: 0
the function is "x * 2 - 3.4" I want to read it with a CIN or something like that


You can't do that in c++. You have to (as you have already done) hard-code the function.

You might, perhaps, restrict the function to, say, a linear form "ax+b" and input the values of a and b. You might (if you have a lot of time on your hands) write your own interpreter that will deal with suitably-formatted expressions. However, you can't do what javascript does with the "eval()" function and actually enter a run-time function. And for all the flexibility of that javascript eval() function, it is also staggeringly dangerous, because you can actually enter any runnable code as well; (for example, code to wipe all your files). So there are very good reasons for c++ not allowing it.


You can also use eval() in Python:
1
2
3
s = input( "Enter an expression: " )
x = float( input( "Enter the value of x: " ) )
print( eval( s ) )

Enter an expression: 2*x+3
Enter the value of x: 5
13.0

https://onlinegdb.com/7Cw_hNBvU

Last edited on
Topic archived. No new replies allowed.