我有这段代码用于评估后修复表达式,并且最初,该代码没有用户输入,但是已经在主函数中定义了这样的表达式:
int main()
{
char exp[] = "100 200 + 2 / 5 * 7 +";
printf ("%d", evaluation(exp));
return 0;
}
它将显示答案
但是,当我将代码更改为]时>
int main() { char exp[100]; printf("Enter an expression:"); scanf("%s", exp); printf ("%d", evaluation(exp)); return 0; }
它不起作用,每次运行它都会给我一个随机数
我真的不明白为什么会这样。如何让函数评估用户输入?
非常感谢您的帮助。谢谢。
这里是完整代码:
/*---------------POSTFIX EVALUATION-----------------------------*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct posteval
{
int head1;
unsigned size;
int* expression;
};
struct posteval* newstack(int size)
{
struct posteval* posteval2=(struct posteval*)malloc(sizeof(struct posteval));
if(!posteval2)
{
return 0;
}
posteval2->expression=(int*)malloc(posteval2->size * sizeof(int));
posteval2->head1= -1;
posteval2->size = size;
if(!posteval2->expression)
{
return 0;
}
return posteval2;
};
// a function to push into the stack for postfix evaluation
void postpush(struct posteval* posteval2, int x)
{
posteval2->expression[++posteval2->head1] = x ;
}
// a function to pop into the stack for postfix evaluation
int postpop(struct posteval* posteval2)
{
if(!nothing(posteval2))
{
return posteval2->expression[posteval2->head1--];
}
return 'E';
}
//a function that checks if the stack has nothing in it
int nothing(struct posteval* posteval2)
{
return posteval2->head1 == -1;
}
//function that evaluates the postfix expressions
int evaluation(char* exp)
{
int i;
int operand;
int explength=strlen(exp);
int num1, num2;
struct posteval* posteval2=newstack(explength);
if (!posteval2)
{
return -1;
}
for(i=0; exp[i]; ++i)
{
if (exp[i]==' ')
{
continue;
}
else if (isdigit(exp[i]))
{
operand=0;
while(isdigit(exp[i]))
{
operand= operand*10 + (int)(exp[i]-'0');
i++;
}
i--;
postpush(posteval2, operand);
}
else {
num1 = postpop(posteval2);
num2 = postpop(posteval2);
if(exp[i]=='/')
{
postpush(posteval2, num2/num1);
}
else if(exp[i]=='+')
{
postpush(posteval2, num2 + num1);
}
else if (exp[i]=='*')
{
postpush(posteval2, num2 * num1);
}
else if (exp[i]=='-')
{
postpush(posteval2, num2 - num1);
}
}
}
return postpop(posteval2);
}
int main()
{
char exp[100];
printf("Enter an expression:");
scanf("%c", exp);
printf ("%d", evaluation(exp));
return 0;
}
}
我有这段代码用于评估后修复表达式,并且最初,该代码没有用户输入,但是已经在主函数中定义了这样的表达式:int main(){char ...
scanf