题目要求:编程实现计算器程序,完成实数的加、减、乘、除运算。注意运算符优先级别。表达式要求采用中缀形式,例如:2.3+7.2*7提示:表达式处理可参考“逆波兰表达式”范例。
完整程序如下:
1 #include
2 #include
3 #include
4
5 #define MAXSIZE 100
6 #define SYMBOLSIZE 50
7
8 //表达式运算符结构体
9 typedef struct oper_symbol
10 {
11 char oper; //运算符
12 unsigned int index;//运算符在表达式中的位置索引
13 }oper_symbol;
14
15 //表达式计算函数声明
16 double caculate(char * expression);
17 double get_data(char * str,int beg,int end);
18 int is_operator_symbol(char ch);
19 long int power(int base,int times);
20
21 int main()
22 {
23 char *expression = NULL;
24 double ret;
25 expression = (char*)malloc(sizeof(char)*MAXSIZE);
26 if(expression == NULL)
27 {
28 printf("内存分配失败.\n");
29 return -1;
30 }
31 memset(expression,0,MAXSIZE*sizeof(char));
32 while(1)
33 {
34 printf("请输入一个表达式: ");
35 scanf("%s",expression);
36 ret = caculate(expression);
37 printf("表达式计算结果为: %lf\n",ret);
38 }
39 free(expression);
40 system("pause");
41 return 0;
42 }
43
44 //表达式计算函数声明
45 double caculate(char * expression)
46 {
47 unsigned int i,j,k;
48 unsigned int symbol_len = 0; //运算符栈的长度
49 unsigned int datas_len = 0; //操作数栈的长度
50 unsigned int symbol_index_len=0; //运算符的个数
51 double left_data,right_data; //左右操作数
52 double temp,ret;
53
54 double *datas = (double*)malloc(sizeof(double)*MAXSIZE);
55 char *symbols = (char*)malloc(sizeof(char*)*SYMBOLSIZE);
56 oper_symbol * symbols_index = (oper_symbol*)malloc(sizeof(oper_symbol)*SYMBOLSIZE);
57
58 if(datas == NULL || symbols == NULL || symbols_index == NULL)
59 {
60 printf("内存分配失败.\n");
61 return 0;
62 }
63 for(i=0;i |