C语言表达评估 [英] Expression evaluation in C language
问题描述
我是理学硕士学位的计算机科学专业的学生.我正在为本科生教授C语言.
考虑这个程序:
Hi,
I''m a Computer Science student in Master of Science degree. I''m teaching c language to undergraduate students.
Consider this program :
#include <stdio.h>
#include <conio.h>
int main() {
clrscr();
float f=4;
float g = f / 4 + f * 2 / ++f;
printf("%5.2f", g);
getch();
}
据我所知,表达是根据运算符的优先级从左到右进行评估的.
此处++的优先级高于+-/*运算符.并且,*/的优先级高于+-运算符.因此,表达式必须计算为:
g = f/4 + f * 2/++ f;
g =(f/4)+((f * 2)/++ f);
........ 1 .... 5 ...... 2 .... 4 ... 3 ....
结果必须是:
g = 2.6
但是,编译器将表达式计算为:
g =(f/4)+((f * 2)/++ f);
........ 4 .... 5 ...... 1 .... 3 ... 2 ....
结果是:
g = 2.85
为什么在没有括号的情况下会发生这种情况?
我在Turbo C和Borland C编译器中测试了此问题.
特别感谢
To my knowledge expression evaluation is done from left to right and based on operators precedence.
Here precedence of ++ is higher than + - / * operators. And, precedence of * / is higher than + - operators. So, the expression must be computed as:
g = f / 4 + f * 2 / ++f;
g = (f / 4) + ((f * 2) / ++f);
........1....5......2....4...3....
and the result must be:
g = 2.6
but, the compiler computes the expression as:
g = (f / 4) + ((f * 2) / ++f);
........4....5......1....3...2....
and the result is:
g = 2.85
Why this happens with no paranthesis in expression ?
I tested this issue in Turbo C and Borland C compilers.
Special Thanks
推荐答案
由于操作符优先级而发生-谷歌将为您提供帮助-这样做确实有道理.
我不会那样做-您实际想要发生的事情并不明显,这使得凡人很难一眼就理解大多数人阅读代码的方式.将其重新处理为两行:它既使我们更清楚,也使编译器更清楚:
It happens because of operator precedence - google will help you with that - so it does make some sense.
I wouldn''t do that - it isn''t obvious what you actually want to happen, and that makes it difficult for a mere mortal to comprehend at a glance - the way most people read code. Re work it to two lines: It both makes it clearer for us, but also for the compiler:
float g = f / 4 + f * 2 / (f + 1);
f++;
我也倾向于添加更多括号以使其变得绝对明显-但是,在此之前,我已经在各种语言之间翻译了代码...
I would also tend to add more brackets to make it absolutely obvious - but then, I''ve translated code between languages before...
float g = (f / 4) + ((f * 2) / (f + 1));
f++;
这篇关于C语言表达评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!