#定义输出不正确 [英] #define output is not correct
问题描述
我输入了以下代码,但无法理解输出内容
i have typed the following code but not able understand the output
#include<iostream.h>
#include<conio.h>
#define AREA(a) a*a;
int area(int a)
{
return a*a;
}
void main()
{
cout<<AREA(5+2);
cout<<"\t"<<area(5+2);
}
</conio.h></iostream.h>
输出为17和49
我无法理解为什么宏将ans设为17而不是49
请通过您的宝贵意见解决这些问题
[edit]已添加代码块,格式为-OriginalGriff [/edit]
@griff
先生
为什么将这样的代码替换为5 + 2 * 5 + 2
能否请您解释一下
and the output is 17 and 49
im not able to understand why macro giving ans as 17 instead of 49
please solve this ques with your valueable comments
[edit]Code blocks added, formatting - OriginalGriff[/edit]
@griff
sir
why this code is replaced like this 5+2*5+2
can you please explain
推荐答案
这很简单-运算符优先级和预处理程序:
使用area(5+2)
时,编译器进行数学运算,并将其更改为对area(7)
的调用-返回7*7
或49.
当您使用AREA(5+2)
时,预处理程序会进行文本替换,并用5+2*5+2
替换它. 然后,运算符在"+"上的"*"优先级将其编译为5 + (2*5) + 2
或17.
要解决此问题,请用
替换您的定义
It''s pretty simple - operator precidence and preprocessors:
When you usearea(5+2)
the compiler does the math, and changes it to a call toarea(7)
- which returns7*7
or 49.
When you useAREA(5+2)
the preprocessor does a text subsitution, and replaces it with5+2*5+2
Operator precidence of the "*" over the "+" then gets it compiled as5 + (2*5) + 2
or 17.
To fix it, replace your definition by
#define AREA(a) ((a)*(a))
杰夫·威廉姆斯(Geoff Williams)正确地指出,为了真正安全,您需要在整个宏定义周围加上方括号,并加以感谢.我发现您绝对不需要分号,最后用腮红将其删除...-OriginalGriff [/edit]
[edit]Geoff Williams correctly pointed out that you need brackets round the whole macro definition to be truely safe, added with thanks. I spotted that you definitely don''t need the semicolon on the end, removed with blushes... - OriginalGriff[/edit]
这篇关于#定义输出不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!