C.

  • Prefix expressions are evaluated recursively

Arithmetic expressions have prefix notation, infix notation, and postfix notation. A prefix expression is a binary operator that precedes two operands. For example, 2+3*(7-4)+8/4 is: + + 2 * 3-7 4/8 4. Please design a program to evaluate the resulting value of the prefix expression.

Let’s look at prefix expressions first:

A prefix expression is also called an inverse Polish expression. An inverse Polish expression consists of the following:

Expression = symbol (+,-,*,/) + number 1 (or subexpression) + number 2 (or subexpression)

Each subexpression requires only two arguments, so arguments can be read at operation time to avoid uncertainty about how much data is being read.

Since the expression form of inverse Polish expression has the characteristics of recursion, we can use the recursive way to deal with inverse Polish expression.

The complete code is as follows:

/* Author: Veeupup */
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int INF = INT32_MAX;

double exp(a)
{
    char a[10];
    scanf("%s", a);
    if (strlen(a) == 1 && !(a[0] > ='0' && a[0] < ='9'))
    { // The length is 1, otherwise it may be a negative number
        switch (a[0])
        {
        case '+':
            return exp() + exp(a);case The '-':
            return exp() - exp(a);case The '*':
            return exp(*)exp(a);case '/':
            double fenzi = exp(a);double fenmu = exp(a);if(fenmu ! =0)
                return fenzi / fenmu;
            else
            {
                printf("ERROR");
                exit(0); }}}else
    {
        return atof(a); }}int main(a)
{
    double ans;
    ans = exp(a);printf("%.1f", ans);
    return 0;
}
Copy the code