C:评估队列中的表达式不起作用 [英] C: Evaluating Expression in a queue not working
问题描述
我使用链接列表创建了一个队列,该队列采用格式为 1 + 3 + 5 =
或 1-3 + 2-4 =
的字符串,但以下内容应该执行给定符号并产生答案的代码无法正常工作,例如,如果我传递了类似 66-31-21-21 + 43 =
的字符串,则答案是 -47
而不是 57
.有人可以帮我解决问题,还是指出我做错了什么.
I have created a queue using linked list that takes a string in the format 1 + 3 + 5 =
or 1-3+2-4 =
but the following code which is supposed to do the calculation given the sign and produce the answer is not working right for example if I passed a string like 66 - 31 - 21 + 43 =
is passed the answer turns out to be -47
instead of 57
. Can someone help me solve it or point to what I'm doing wrong.
void printQueue(struct node* head)
{
struct node* temp;
char *token, *del=" ";
int total = 0;
while (head != NULL)
{
token = strtok(head->data, del);
while (token != NULL) {
int a = strcmp(token, "+");
int b = strcmp(token, "-");
if (a == 0)
{
printf("+");
total = total + *token;
}
else if (b == 0) {
printf("+");
total = total - *token;
}
printf("%s ", token);
token = strtok(NULL, del);
}
printf(" %d\n",subtraction);
head = head->next;
}
}
推荐答案
您的代码忽略了数字,将'+'
和'-'
的字符代码相加字符代替.数字 -47
是-45-45 + 43的计算结果:45是破折号的字符代码;加号的字符代码为43.
Your code is ignoring the numbers, adding up character codes of '+'
and '-'
characters instead. The number -47
is the result of computing -45-45+43: 45 is the character code for the dash; 43 is the character code for the plus.
为了正常工作,请对您的代码进行以下更改:
In order to work properly, make these changes to your code:
- 添加
int
类型的sign
变量,其初始值为1
- 看到加号时,请将
sign
设置为1
- 看到减号时,请将
sign
设置为-1
- 当您看到既不是加号也不是减号的令牌时,请将其转换为
int val
(例如,通过调用atoi
),然后添加val *签名
到运行总计.
- Add a
sign
variable ofint
type, with the initial value of1
- When you see a plus sign, set the
sign
to1
- When you see a minus sign, set the
sign
to-1
- When you see a token that is neither a plus nor minus, convert it to an
int val
(e.g. by callingatoi
), and addval * sign
to the running total.
此更改将使您的代码适用于有效的表达式,但对于某些无效的表达式也不会失败.例如,将采用诸如 1 2 3
之类的表达式",就好像它是 1 + 2 + 3
一样,依此类推.
This change will make your code work for valid expressions, but it would not fail for some invalid ones. For example, it would take "expressions" such as 1 2 3
as if it were 1+2+3
, and so on.
这篇关于C:评估队列中的表达式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!