表达式树-带字符的运算 [英] Expression Tree - Operations with Characters
本文介绍了表达式树-带字符的运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
4*5+2/3
这样的操作输入一个字符串,代码应该根据它和计算所述表达式树来生成表达式树。我遇到一个问题,程序使用ASCII表的十进制值而不是实际数字创建表达式树。
例如,程序存储并使用52 42 53 43 50 47 51
进行计算,而不是4*5+2/3
。我想要的运行屏幕是:
1 //this is the number of strings
4*5+2/3 //this is the string itself
20 //this is the result
但是,我得到的是:
1 //this is the number of strings
4*5+2/3 //this is the string itself
2756 //this is the result
这是因为代码执行的是52*53+50/51
(因为它使用的是ASCII值),而不是4*5+2/3
。
我认为这是因为我将4*5+2/3
存储在char
的字符串中,而不是存储在int
的数组中。我不知道情况是否如此,需要一些帮助。
这是我的Make Expression Tree函数和Calculate Expression Tree函数:
BTreeNode* MakeExpTree(char* exp, int len)
{
Stack stack;
BTreeNode * node, *right_node, *left_node;
InitStack(&stack);
for(int i = 0; i < len; i++){
if('0' <= exp[i] && exp[i] <= '9'){
node = CreateNode(exp[i]);
}
else{
right_node = PeekNode(&stack), Pop(&stack);
left_node = PeekNode(&stack), Pop(&stack);
node = CreateNode(exp[i]);
CreateRightSubtree(node, right_node);
CreateLeftSubtree(node, left_node);
}
PushNode(&stack, node);
}
return PeekNode(&stack);
}
int CalculateExpTree(BTreeNode* root)
{
int ret, op1, op2;
if(root == NULL){
return 0;
}
if(root->left_child == NULL && root->right_child == NULL){
return root->item;
}
op1 = CalculateExpTree(root->left_child);
op2 = CalculateExpTree(root->right_child);
switch(root->item){
case '+':
ret = op1 + op2;
break;
case '-':
ret = op1 - op2;
break;
case '*':
ret = op1 * op2;
break;
case '/':
ret = op1 / op2;
break;
case '@':
ret = op1 * pow( 2, op2);
break;
case '#':
ret = op1 / pow( 2, op2);
break;
}
return ret;
}
这就是我在main函数中存储stdin中的字符串的方式:
int main()
{
int num_exp, result, len = 0;
char input[10];
char IDK[129];
fgets(input, 9, stdin); //user enters number of strings
int m = sscanf(input, "%d", &num_exp);
char string[100][129] = { 0 };
char postfix[100][129] = { 0 };
for(int i = 0; i < num_exp; i++){
fgets(IDK, 129, stdin); //user enters string
int mm = sscanf(IDK, "%s", string[i]); //is this where the problem lies?
} //should I not be storing it in a char string?
for(int x = 0; x < num_exp; x++){
InfixToPostfix(string[x], postfix[x]); //converts strings from infix to postfix
}
BTreeNode* tree;
for(int k = 0; k < 129; k++){ //calculates length of string
if(postfix[0][k] == ' '){
break;
}
len++;
}
tree = MakeExpTree(postfix[0], len); //makes expression tree
result = CalculateExpTree(tree); //calculates expression tree
//or is the problem in this function?
printf("%d
", result);
return 0;
}
推荐答案
这是因为代码执行的是
52*53+50/51
(因为它使用的是ASCII值),而不是4*5+2/3
。
是。
我认为这是因为我将
4*5+2/3
存储在一个字符字符串中,而不是存储在一个int数组中。
否
在C中,int
只是一个较大的char
。它们没有什么神奇之处;它们都拿着数字。
static char string[] = "4";
int value = string[0] & 0x0F;
做到了这一点。对于更复杂的操作,我最喜欢使用sscanf(3),但很多人使用atoi(3)或各种风格的strtol(3)。
这篇关于表达式树-带字符的运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文