gpt4 book ai didi

c - 如何正确解析算术表达式中的数字,区分正数和负数?

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:58 25 4
gpt4 key购买 nike

我在我的数据结构类中有一个作业,我必须在其中编写一个计算器,用 4 个基本运算和括号来求解算术表达式,输入是通过标准输入缓冲区完成的,输出也是如此。

一开始很容易,老师给了我们算法(如何将表达式从中缀转换为后缀以及如何对其进行评估),唯一的目标是让我们实现自己的堆栈并使用它,但是计算器本身不能很好地工作,我认为这是因为我的解析器。

This is the algorithm ,以及我的代码,用于解析数字、运算符和括号,同时将它们放入一个数组中,以便以一种更易于日后评估的方式存储表达式。

// 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 - (),但这是另一个问题。

感谢您的帮助。

最佳答案

这就是所谓的“一元减号”问题,在您的情况下(无变量)可以通过替换来解决。

运算符 - 是一元减号,如果是的话

  • 前面有一个左括号
  • 前面是另一个运算符(operator)
  • 输入的第一个字符

现在不是存储 -,而是存储一个不同的字符,例如 m 并为其分配比其他运算符更高的优先级(或与求幂运算符相同)如果你有的话)。

另一个提示:不要使用空格来表示任何内容,算术表达式必须在没有任何空格的情况下工作,否则它是不正确的。

关于c - 如何正确解析算术表达式中的数字,区分正数和负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com