我的rpn-calculator工作,但有问题。问题在于它会打印出每个连续的计算结果。在哪里放置printf以避免在我的rpn计算器中进行多次打印?
我已经尝试了不同的方法来解决这个问题,最新的一个是添加一个整数,每个计算都会增加一个整数,如果这个整数高于0,以及只有一个数字在堆栈上打印。
但是,如果有多个计算正在进行(例如,写入5 5 + 10 5 * *),则会导致打印出10 500个问题,因为第一次计算后堆栈中只有一个项目。
我该如何解决这个问题?
#define MAX_STACK_SIZE 100
#define MAX_BUFFER_SIZE 100
char buff[MAX_BUFFER_SIZE];
double x, stack[MAX_STACK_SIZE];
double t;
int i, k=0, num_operand=0;
int main(void) {
while(x != 'q') {
if(scanf("%s", buff) < 1)
{ return 0;
}
if(isdigit(buff[0]) || isdigit(buff[1])) {
sscanf(buff, "%lf", &x);
if (num_operand < MAX_STACK_SIZE)
{
stack[num_operand]=x;
num_operand ++;
} else { printf("Make stack bigger\n");}
} else {
switch(buff[0]) {
case '+': stack[num_operand - 2] = stack[num_operand - 1] + stack[num_operand - 2];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '-': stack[num_operand - 2] = stack[num_operand - 2] - stack[num_operand - 1];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '/': stack[num_operand - 2] = stack[num_operand - 2]/stack[num_operand - 1];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '*': stack[num_operand - 2] = stack[num_operand - 1] * stack[num_operand - 2];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
} }
if (num_operand == 1 && k !=0) {
k = 0;
printf("%lf \n", t); }
}
}
'x!='q'':'x'的类型是双倍的。 – BLUEPIXY
阅读整个表达式然后对其进行评估,而不是在阅读时逐位评估表达式。 – molbdnilo
注意:'printf(“%lf \ n”,t);'不会打印“10 500”,而是“10.000000 \ n500.000000 \ n”'。细节很重要。 – chux