[问题] 后输入运算式,堆叠后归零

楼主: justgetup (gonna fight)   2021-11-27 02:14:03
开发平台(Platform): (Ex: Win10, Linux, ...)
DEVC++
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
问题(Question):
在PUSH(sum)完资料后 用sum=0清空,但之后sum输入的资料都变成0
喂入的资料(Input):
预期的正确结果(Expected Output):
可以正常的四则运算
错误结果(Wrong Output):
结果都为0
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
int postfixEval(char *exp) {
int operand1 = 0; /* 第1个算子变量 */
int operand2 = 0; /* 第2个算子变量 */
int sum = 0; /* 判断式所需之变量 */
int pos = 0; /* 运算式字串索引 */
/* 剖析运算式字串循环 */
while ( exp[pos] != '\0' && exp[pos] != '\n' ) {
if ( isOperator(exp[pos]) ) { /* 是不是运算子 */
/* 是运算子,从堆叠取出两个算子 */
operand1 = pop();
operand2 = pop();
/* 计算结果存回堆叠 */
push(cal(exp[pos],operand2,operand1));
}
else
if (exp[pos] >= '0' && exp[pos] <= '9')
*/
sum = sum*10+(exp[pos]-'0');
else
push(sum);
sum = 0;
pos++; /* 下一个字符 */
}
return pop(); /* 传回后序运算式的结果 */
}
补充说明(Supplement):
想法是一个字符读完,如果下一个也是字符就sum=A*10+B,遇到空格
push(sum),然后sum归0,再遇到下一个字符时重复
作者: Schottky (顺风相送)   2021-11-27 03:22:00
缺乏输入资料。话说你怎么确定有空格,题目有规定吗?然后你犯了新手错误,sum=0那行不在else内,变成每次都执行,请用大括号把else后的两行包起来
楼主: justgetup (gonna fight)   2021-11-27 10:13:00
题目有规定用空格分开数字 已经解决了 谢谢

Links booklink

Contact Us: admin [ a t ] ucptt.com