运算字符的解析,如:43+表示:4+3, 25* 表示:2*5, 25*1+表示(2*5)+1,435/+表示:4 +(3/5)
1 #include <stdio.h>
2 #include <stdbool.h>
3 #include <string.h>
4
5 bool isNumber(const char *c);
6 int getNumber(const char *c);
7 bool isOperator(const char *c);
8 float calculate(char *string, int len);
9
10 int main(int argc, const char * argv[])
11 {
12
13 // insert code here...
14 printf("Begin>>\n");
15 printf("%d",‘0‘);
16 printf("%d\n",‘/‘);
17 char string[100] = "435/+";
18 size_t len = strlen(string);
19 float ret = calculate(string, (int)len);
20 printf("result = %f\n", ret);
21 return 0;
22 }
23
24 bool isNumber(const char *c)
25 {
26 if ( (int)(*c) >= (int)(‘0‘) && (int)(*c) <= (int)(‘9‘)) {
27 return true;
28 }
29 return false;
30 }
31
32 int getNumber(const char *c)
33 {
34 bool isN = isNumber(c);
35 if (isN) {
36 int n = (int)((*c) - (int)‘0‘);
37 return n;
38 }else {
39 return 0;
40 }
41 }
42
43 bool isOperator(const char *c)
44 {
45 if ((int)(*c) == (int)‘+‘ || (int)(*c) == (int)‘-‘ || (int)(*c) == (int)(‘*‘) || (int)(*c) == (int)(‘/‘) ) {
46 return true;
47 } else {
48 return false;
49 }
50
51 }
52
53 float calculate(char *string, int len)
54 {
55 if (len == 1) {
56 return (float)getNumber(string);
57 }
58
59 if (len == 2) {
60 printf("error!");
61 }
62
63 if (!isOperator(string + len - 1)) {
64 return 0.0f;
65 }
66
67 float a = 0.0f;
68 float b = 0.0f;
69 if (isOperator(string + len - 1 -1)) {
70 a = (float)getNumber(string);
71 b = calculate(string + 1, len - 2);
72 } else {
73 a = calculate(string, len - 2);
74 b = (float)getNumber(string + len - 1 - 1);
75 }
76
77 char operator = *(string + len - 1);
78 if ((int)operator == (int)‘+‘) {
79 return (a + b);
80 } else if ((int)operator == (int)‘-‘) {
81 return (a - b);
82 } else if ((int)operator == (int)‘*‘) {
83 return (a * b);
84 } else if ((int)operator == (int)‘/‘) {
85 return (a / b);
86 } else {
87 return 0.0f;
88 }
89
90 }
时间: 2024-10-07 07:43:23