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

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指向下一个运算符或'\0'.
{
    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 != '\0')
    {
        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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值