华为机试——四则运算表达式求值

C_C++_XY_05.四则运算表达式求值

  • 题目描述:

实现一个正整数加、减、乘、除四则混合运算求值方法

条件限定:

1、 输入的四则运算式由'+','-','*','/'运算符及正整数组成;

2、 无需考虑特殊字符,及除不尽的情况;

3、 无需考虑运算符的优先级,加减乘除优先级一样,仅按照自左至右的顺序依次计算;

4、 当遇到除数为0时,即刻返回当前已计算结果。

  • 要求实现函数:

void CalCarithmeticRlt(const char *pInputStr, int *lOutputRlt);

【输入】 pInputStr: 输入字符串

【输出】 lOutputRlt: 输出计算结果

【注意】不用考虑输入四则运算式非法情况

  • 示例

输入:“2+1*4-2/5”

输出:“2”

注意:无需用double(题目要求不考虑除不尽的情况).

思路:

"2+100*4-10000/25"

参与运算的可能是多位数,所以要将多位数转换为int型,

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

#include <iostream>
#include <ctype.h>
using namespace std;
 
int convertToDigit(const char *&str)//将从str开始的数字即其后的数字转换为int,最终str指向下一个运算符或''.
{
    int result = 0;
 
    while (isdigit(*str))
    {
        result = result * 10 + (*str - '0');
        str++;
    }
 
    return result;
}
 
void CalCarithmeticRlt(const char *pInputStr, int *lOutputRlt)
{
    //ignore invalid input.
 
    int rightNum;
    int leftNum = convertToDigit(pInputStr);; //convert to digit.
 
    while (*pInputStr != '')
    {
        char tmp = *pInputStr;//pInputStr指向运算符。
        rightNum = convertToDigit(++pInputStr);//调用完后,pInputStr指向下一个运算符。
 
        switch (tmp)
        {
            case '+':
                leftNum = leftNum + rightNum;
                break;
            case '-':
                leftNum = leftNum - rightNum;
                break;
            case '*':
                leftNum = leftNum * rightNum;
                break;
            case '/':
            {
                if (rightNum == 0)
                {
                    *lOutputRlt = leftNum;
                    return ;
                }
                else
                {
                    leftNum = leftNum / rightNum;
                }
                break;
            }
            default:
                break;
        }
    }
 
    *lOutputRlt = leftNum;
}
 
 
int main() {
    const char *pInputStr = "2+100*4-10000/25";
//     const char *pInputStr = "2+10*4-1/47";
    int lOutputRlt;
    CalCarithmeticRlt(pInputStr, &lOutputRlt);
 
    cout << lOutputRlt << endl;
 
 
    return 0;
 
 
}
原文地址:https://www.cnblogs.com/helloweworld/p/3201437.html