我在数据结构类中有一个作业,其中我必须编写一个计算器,用 4 个基本运算和括号来求解算术表达式,输入是通过 stdin 缓冲区完成的,输出也是如此。
一开始很简单,老师给我们提供了算法(如何将表达式从中缀转换为后缀以及如何对其求值),唯一的目标是让我们实现自己的堆栈并使用它,但是计算器它本身并不能很好地工作,我认为这是因为我的解析器。
这是算法和我的代码,用于解析数字、运算符和括号,同时将它们放入数组中,以便以以后更容易计算的方式存储表达式。
// saida is an array of pairs of integers, the first value of the pair is the value of the info (the number itself or the ASCII value of the operator)
// The second value is an indicator of whether it is a number or a operator
for (i = 0; i < exp_size; i++) {
c = expression[i];
// If the current char is a digit, store it into a helper string and keep going until a non-digit is found
// Then atoi() is used to transform this string into an int and then store it.
if (c >= '0' && c <= '9') {
j = 1, k = i+1;
tempInt[0] = c;
while(expression[k] >= '0' && expression[k] <= '9') {
tempInt[j++] = expression[k];
k++;
}
tempInt[j] = '\0';
saida[saidaIndex][0] = atoi(tempInt);
saida[saidaIndex++][1] = 0;
i = k-1;
}
// If the character is an operator, the algorithm is followed.
else if (c == '+' || c == '-' || c == '*' || c == '/') {
while(pilha->size > 0 && isOpBigger( stack_top(pilha), c )) {
saida[saidaIndex][0] = stack_pop(pilha);
saida[saidaIndex++][1] = 1;
}
stack_push(c, pilha);
}
else if (c == '(') stack_push(c, pilha);
else if (c == ')') {
j = stack_pop(pilha);
while(j != '(') {
saida[saidaIndex][0] = j;
saida[saidaIndex++][1] = 1;
j = stack_pop(pilha);
}
}
}
问题是,在这段代码中我无法判断减号是否表示减法运算符或负数(我知道减号运算符是与负数相加,但这并没有帮助我解决这个问题) ,我想到了以下内容,但没有成功:
- 每次出现减号时,存储一个加号,并让下一个数字本身 * -1。如果下一个数字已经是负数或者减号位于带有括号的表达式(例如 1 + 2 - (3 * 4))之前,则不起作用。
- 如果减号后面有空格,则为运算符,如果没有,则为负数。不起作用,因为输入上没有这些规则。
我没有任何口译经验,我真的不知道如何进行。该代码可以完美地处理没有负数的有效表达式,但不能处理像 () + 3 - () 这样的奇怪表达式,但这是另一个问题。
谢谢你的帮助。
这就是所谓的“一元减”问题,在您的情况下(没有变量)可以通过替换来解决。
运营商-
是一元减号,如果是
- 前面有一个左括号
- 前面有另一个运算符
- 输入的第一个字符
现在而不是存储-
你存储一个不同的字符,比如m
并为其指定比其他运算符更高的优先级(或者与求幂运算符相同,如果有的话)。
另一个提示:不要使用空格来表示任何内容,算术表达式必须在没有任何空格的情况下工作,否则它是不正确的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)