华为上机练习题--简单加减表达式计算

题目:

通过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。
输入字符串的格式为:“操作数1 运算符 操作数2”,“操作数”与“运算符”之间以一个空格隔开。

补充说明:
1、操作数为正整数,不须要考虑计算结果溢出的情况。
2、若输入算式格式错误,输出结果为“0”。

要求实现函数:
void arithmetic(const char *pInputStr, long lInputLen, char *pOutputStr);

【输入】 pInputStr:  输入字符串
            lInputLen:  输入字符串长度        
【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;

【注意】仅仅须要完毕该函数功能算法,中间不须要有不论什么IO的输入输出

演示样例
输入:“4 + 7”  输出:“11”
输入:“4 - 7”  输出:“-3”
输入:“9 ++ 7”  输出:“0” 注:格式错误


分析:先切割字符串,分别取得两个操作数和一个运算符, 然后再做一些非法推断, 最后进行运算操作;


代码例如以下:

package com.wenj.test;

/**
 *
 * @author wenj91-PC
 *
 */

public class TestArithmetic {

    public static void main(String args[]){
        String strIn = "9 ++ 7";
        TestArithmetic ta = new TestArithmetic();
        System.out.println(ta.arithmetic(strIn));
    }
    
    public int arithmetic(String strIn){
        String strTemp = strIn;
        String[] strArr = strTemp.split(" ");
        int a, b;
        try{
            a = Integer.parseInt(strArr[0]);
            b = Integer.parseInt(strArr[2]);
        }catch(Exception e){
            return 0;
        }
        
        String mid = strArr[1];
        char[] strC = mid.toCharArray();
        if(strC.length > 1){
            return 0;
        }
        
        switch(strC[0]){
        case '+':
            return (a+b);
        case '-':
            return (a-b);
        default:
            return 0;
        }
    }
}

原文地址:https://www.cnblogs.com/mfrbuaa/p/4266792.html