Reputation: 931
Here is a very basic program that simulates a log x(y) function.
I would like to know if it is possible to input a mathematical operation in the cin function.
For example to calculate log2(1/8) ? So input 2 for x and 1/8 for y
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x(0.0);
double y(0.0);
cout << "log" << endl;
cin >> x;
cout << "result" << endl;
cin >> y;
double loga = log(y) / log(x);
cout << "log" << x << "(" << y << ") =" << loga << endl;
cout << loga << "^" << x << "="<< pow(x, loga)<< endl;
return 0;
}
thank you for your help
Upvotes: 0
Views: 3657
Reputation: 50061
No, cin
cannot do that. You would have to read the expression as a string, then parse it and evaluate it to a number.
Resources on how to do this for simple cases are easily found online and there are powerful libraries that can do the work for you.
Upvotes: 1
Reputation: 20891
cin
doesn't support your intent. However, you can follow an approach that hold your fractional expression in a string than convert it as double value. So go on.
Upvotes: 1
Reputation: 1
I would like to know if it is possible to input a mathematical operation in the cin function.
It's only possible by means you write your own parser, that translates the input achieved from std::cin
or any other std::istream
source that isn't covered from any standard translations like int
, long
, float
, std::string
etc.
Do you should provide logic to parse the input you get and translate that to values and function call logic.
Upvotes: 1