在C异常输出 [英] Unexpected output in c
本文介绍了在C异常输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新的C语言编写。我只是想知道为什么工作不正常我的宏。这是给我输出13在那里我的预期成果是24?
#包括LT&;&stdio.h中GT;
的#define MULT(A,B)A * B
诠释的main()
{
INT X = 4,Y = 5;
的printf(%d个,MULT(X + 2,Y-1));
返回0;
}
解决方案
在宏定义使用括号
#包括LT&;&stdio.h中GT;
的#define MULT(A,B)((A)×(B))
诠释的main()
{
INT X = 4,Y = 5;
的printf(%d个,MULT(X + 2,Y-1));
返回0;
}
这是因为不同的算术运算符有不同的precedence水平。因此,尽管定义宏总是用括号。
I am new to c language. I just wanted to know why is my macro not working properly. It is giving me output as 13 where as my expected output is 24.?
#include<stdio.h>
#define mult(a,b) a*b
int main()
{
int x=4,y=5;
printf("%d",mult(x+2,y-1));
return 0;
}
解决方案
Use parentheses in the macro definition
#include<stdio.h>
#define mult(a,b) ((a)*(b))
int main()
{
int x=4,y=5;
printf("%d",mult(x+2,y-1));
return 0;
}
This is because different arithmetic operators have different precedence levels. Hence always use parentheses while defining the macro.
这篇关于在C异常输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文