- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在我的数据结构类中有一个作业,我必须在其中编写一个计算器,用 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);
}
}
}
问题是,在这段代码中,我无法判断减号是表示减法运算符还是负数(我知道减号运算符是负数的和,但它并没有帮助我解决这个问题),我想到了以下,但都没有成功:
我没有任何口译经验,我真的不知道如何进行。该代码可以完美地处理没有负数的有效表达式,但不能处理奇怪的表达式,例如 () + 3 - (),但这是另一个问题。
感谢您的帮助。
最佳答案
这就是所谓的“一元减号”问题,在您的情况下(无变量)可以通过替换来解决。
运算符 -
是一元减号,如果是的话
现在不是存储 -
,而是存储一个不同的字符,例如 m
并为其分配比其他运算符更高的优先级(或与求幂运算符相同)如果你有的话)。
另一个提示:不要使用空格来表示任何内容,算术表达式必须在没有任何空格的情况下工作,否则它是不正确的。
关于c - 如何正确解析算术表达式中的数字,区分正数和负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196777/
所以我目前正在代码 war 中解决以下问题: 返回一个数组,其中第一个元素是正数的计数,第二个元素是负数的总和。如果输入数组为空或 null,则返回一个空数组。 我想出了下面的代码,它并不漂亮,但我知
我想禁用文本框中的字母,这就是我使用此表达式的原因: /^[0-9]*$/ 问题是我也想允许负数, 这个表达式不允许我使用减号。(-)..我该怎么办? 最佳答案 尝试使用以下正则表达式: /^-?[0
这是一道面试题。我们有一个正整数数组,我们必须重新排列和连接数组元素,以便生成的数字是可以使用此数组形成的最大数字。 例如: [884 88] -> 88884 [20 19 90] -> 90201
所以我有点无奈。我想我了解如何对 IEEE-754 数字进行加法,但我在减法方面遇到了很大的问题。我感觉我的想法是对的,但我想和大家确认一下。 因此我们有以下两个 IEEE-754 编号: x: 0
我想将一个正数转换成相应的数字列表——数字也应该是整数。 转换时,比如1024,应该返回[1,0,2,4] 最佳答案 在 Swift 4.1 或更高版本中 let number = 1024 let
如果 float 可以用来正确表示我将使用的参数范围,我正在尝试为我的音频应用程序弄清楚。 它需要的“最大”掩码用于频率参数,它是正的,并且允许最多两位数字作为尾数(即从 20.00 hz 到 220
我是一名优秀的程序员,十分优秀!