请问一下计算机是如何判断字符的优先级的?
比如%优先级比+高但是在计算机中是应该怎么写代码才能让计算机识别,还是本来计算机就知道它们的优先级?
谢谢 计算机只会执行指令,不会识别什么优先级的.
那些都通过编译器进行的. LS相当于没有回答问题……
其实计算机里面有个表格,标出了所有的优先级关系。
但是表格太大了。所以有些方法来“压缩”这个表。比如用优先级函数代替优先级表。
具体你可以查看“编译原理”的课程,“算符优先算法”。 嗯,你去看看C语言后面的“运算符与优先级”的附录,里面就是编译器翻译代码时所遵守的。
LZ你说“本来计算机就知道它们的优先级”是不对的,又不是ASCII码,怎么可能“本来就知道”,是不[em03]
都是写编译器的程序员通过程序来写好的 事实上,就算是ASCII码,如果没有那个表,计算机也是不知道的~~~ ——嗯 哦 编译原理很重要的哦~~~继续学... 编译原理对于考研很重要 编译原理里面写得很清楚,具体的怎么弄的忘了。 简单的说是编译器的问题,我们控制不了,也不能完全解释明白,悟吧.
这个是自己写的,用来判断 + - * / 的优先级
#include <stdlib.h> /*输入表达式 如 3+8+7*9/2 */struct s_node
{
int data;
struct s_node * next;
};
typedef struct s_node s_link;
typedef s_link *link;
link operand=NULL;
link operator=NULL;
link push (link stack,int value)
{
link new;
new=(link) malloc (sizeof(s_link));
if (!new) printf("allocation failed:\n");
else {
new->data=value;
new->next=stack;
stack=new;
}
return stack;
}
link pop (link stack, int *value)
{
link top;
top=stack;
if (stack!=NULL)
{
stack=stack->next;
*value=top->data;
free(top);
return stack;
}
}
int empty (link stack)
{
if (stack==NULL)
return 1;
else return 0;
}
int is_operator(char operator)
{
switch(operator)
{
case '*' : case '/' : case '+': case '-': return 1;
default: return 0;
}
}
int priority (char operator)
{
switch (operator)
{
case '-': case '+': return 1;
case '*' : case '/' : return 2;
default : return 0;
}
}
int result (int operator, int operand1,int operand2)
{
switch (operator)
{
case '*' : return operand2*operand1;
case '/' : return operand2/operand1;
case '-' : return operand2-operand1;
case '+' : return operand2+operand1;
}
}
void main()
{
char e[50]; int a[5];
int p=0;
int operand1,operand2;
int op;
int evaluate;
printf("\n please input the order expression:");
clrscr();
gets (e);
while (e[p]!='\0' && e[p]!='\n')
{
if (is_operator(e[p]))
{
if (!empty(operator))
{
while (priority(e[p])<=priority(operator->data))
{
operand=pop(operand,&operand1);
operand=pop(operand,&operand2);
operator=pop(operator,&op);
operand=push(operand,result(op,operand1,operand2));
}
}
operator =push(operator,e[p]); p++;
}
else
{
int temp=0;int t=0;int i; int x;int c=0;int b=1;
a[temp]=e[p]-48;
p++;
while (!is_operator(e[p]) && e[p]!='\0')
{
a[++temp]=e[p++]-48;
}
for (i=temp;i>=0;i--)
{
x=i;
while (x)
{
b*=10;
x--;
}
a[c++]*=b;b=1;
}
for (i=temp;i>=0;i--)
t+=a[i];
operand=push (operand,t);
}
}
while (!empty(operator))
{
operator=pop(operator,&op);
operand = pop(operand,&operand1);
operand = pop(operand,&operand2);
operand=push(operand,result(op,operand1,operand2));
}
operand=pop(operand,&evaluate);
printf("the expression [%s] result is '%d'",e,evaluate);
} 服了11#的
页:
[1]
