Question:
Enter the plus or minus formula for positive integers less than 100 on the keyboard. Write a program to output the computation result string.
The format of the input string is "operand 1 operator operand 2", and "operand" and "operator" are separated by a space.
Note:
1. the operand is a positive integer and computing result overflow is not required.
2. If the input formula format is incorrect, the output result is "0 ".
Required implementation functions:
Void Arithmetic (const char * pinputstr, long linputlen, char * poutputstr );
[Input] pinputstr: input string
Linputlen: length of the input string
[Output] poutputstr: Output string. The space has been opened up and the length of the input string is equal to that of the input string;
[Note] You only need to complete the function algorithm, and there is no IO input or output in the middle.
Example
Input: "4 + 7" output: "11"
Input: "4-7" output: "-3"
Input: "9 + + 7" output: "0" Note: Incorrect format
Analysis: splits the string, obtains two operands and one operator, then makes some illegal judgments, and finally performs operations;
The Code is as follows:
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;
}
}
}