Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input a mathematical expression from keyboard? [closed]

Tags:

c++

c

I have a simple C program

int main()
{

    int n, maxn = 21;
    float SN, x;

    printf("input x:");
    scanf("%f", &x);

    printf("input maxn:");
    scanf("%d", &maxn);

    for(n=0;n<=maxn;n++){
        SN = SN + pow(x,n);
        n = n + 1;
    }

    printf("%f", SN);
    getch();
    return 0;
}

I need to make it versatile so the user can enter any expression to replace pow(x, n) with whatever the user inputs from keyboard. How do I put an expression into the program?

like image 832
Euphe Avatar asked Feb 09 '14 10:02

Euphe


People also ask

How do you close something using the keyboard?

Alt + F4 is a keyboard shortcut that completely closes the application you're currently using on your computer. Alt + F4 differs slightly from Ctrl + F4, which closes the current tab or window of the program you're currently using.

How do you type math symbols on a mobile keyboard?

If you have the English (India) keyboard selected, then use the keys combination 'CTRL + ALT + 4' to get the Indian Rupee Symbol (₹). Otherwise follow the steps below: Type 'Control Panel' in search input at bottom-left corner of your screen. Select/Click 'Control Panel Desktop app' from the search results.


1 Answers

C and C++ don't offer you this feature already implemented because there is a clear cut between the compile time (when expressions are analyzed syntactically) and run time (when they're evaluated).

Implementing a parser and compiler/evaluator for expression is a good exercise but it's not trivial and would probably require a lot more experience than you have at this moment (given the question you asked).

The easiest to understand approach to this problem is in my opinion a recursive descent parser but for just the four operations, numbers and variables I'd guess it would require a hundred or so lines of code.

yacc and bison are tools that were designed to generate automatically parsing/evaluation code from a definition of a grammar. I personally prefer to hand-write parsers because of the finer control you get (especially on error handling or when the syntactic and semantic level interact, but that's me and I'm also a bad case of NIH syndrome).

Higher level languages like Python or Javascript instead offer you this feature already implemented as eval.

like image 86
6502 Avatar answered Oct 05 '22 15:10

6502