我想制作一个可以用逻辑运算符计算的计算器。我创建了两个堆栈,其中一个用于1和0,另一个用于运算符。我也可以编译,但是当我想尝试它时,说:“分段错误(核心转储)”。提前谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Stack.h>
#define MAX_EXPR_SIZE 100
int Evaluate01(char *expr) {
int final, i = 0;
Stack *stack1 = (Stack *)malloc(sizeof(Stack));
Stack *stack2 = (Stack *)malloc(sizeof(Stack));
if(!stack1 || !stack2) {
//print error and return
}
Stack_initialize(stack1);
Stack_initialize(stack2);
do {
if (expr[i] == '0' || expr[i] == '1'){
int foo3 = expr[i] - '0';
Stack_Push(stack1, foo3);
}
else if (expr[i] == 0x96){
int foo3 = Stack_Pop(stack1);
int sum = !foo3;
Stack_Push(stack1, sum);
}
else if (expr[i] == 0x62 ||
expr[i] == 0x46 ||
expr[i] == 0x43 ||
expr[i] == 'x'){
Stack_Push(stack2, expr[i]);
}
else if (expr[i] == 0x41){
int sum;
int foo1= Stack_Pop(stack1);
int foo2 = Stack_Pop(stack1);
char op = Stack_Pop(stack2);
switch(op){
case 0x62:
sum = !foo1 || foo2;
Stack_Push(stack1, sum);
break;
case 0x46:
sum = foo1 && foo2;
Stack_Push(stack1, sum);
break;
case 0x43:
sum = foo1 || foo2;
Stack_Push(stack1, sum);
break;
case 'x':
sum = foo1 ^ foo2;
Stack_Push(stack1, sum);
break;
}
}
i++;
}while (expr[i] != '\0');
final = Stack_Pop(stack1);
free(stack1);
free(stack2);
return final;
}
int main(int argc, char *argv[]) {
char expr[MAX_EXPR_SIZE+1];
while(1) {
printf("logical expression : ");
scanf(" %s", expr);
printf("results: ");
printf("%d\n", Evaluate01(expr));
}
return 0;
}
修改:现在它正在运作。非常感谢你!
答案 0 :(得分:1)
首先,当你使用字符及其ascii值之间的比较时,你应该使用hexa base。例如:
expr[i] == 62
应写成:
expr[i] == 0x62
其次,当你将字符转换为int时,你应该使用atoi。
此外,您应首先检查分配是否成功。 最后,while迭代应循环,而expr [i]!= NULL。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Stack.h>
#define MAX_EXPR_SIZE 100
int Evaluate01(char *expr) {
int i = 0;
Stack *stack1 = (Stack *)malloc(sizeof(Stack));
Stack *stack2 = (Stack *)malloc(sizeof(Stack));
if(!stack1 || !stack2) {
//print error and return
}
Stack_initialize(stack1);
Stack_initialize(stack2);
do {
if (expr[i] == '0' || expr[i] == '1'){
int foo3 = atoi(expr[i] - '0');
Stack_Push(stack1, foo3);
}
else if (expr[i] == 0x96){
int foo3 = Stack_Pop(stack1);
int sum = !foo3;
Stack_Push(stack1, sum);
}
else if (expr[i] == 0x62 ||
expr[i] == 0x46 ||
expr[i] == 0x43 ||
expr[i] == 0x120){
Stack_Push(stack2, expr[i]);
}
else if (expr[i] == 0x41){
int sum;
int foo1= Stack_Pop(stack1);
int foo2 = Stack_Pop(stack1);
char op = Stack_Pop(stack2);
switch(op){
case 0x62:
sum = !foo1 || foo2;
Stack_Push(stack1, sum);
break;
case 0x46:
sum = foo1 && foo2;
Stack_Push(stack1, sum);
break;
case 0x43:
sum = foo1 || foo2;
Stack_Push(stack1, sum);
break;
case 0x120:
sum = foo1 ^ foo2;
Stack_Push(stack1, sum);
break;
}
}
i++;
}while (expr[i] != NULL);
free(stack1);
free(stack2);
}
int main(int argc, char *argv[]) {
char expr[MAX_EXPR_SIZE+1];
while(1) {
printf("logical expression : ");
scanf(" %s", expr);
printf("results: ");
printf("%d\n", Evaluate01(expr));
}
return 0;
}