输入2,3,10的下面代码用于给出12.5作为结果.([sum(2,3,10)(= 15)+ maximum(2,3,10)(= 10)] /最小(2,3,10)(= 2))但结果输出2.000,这是不需要的和错误的.我是在做出优先级错误还是我犯了什么样的错误?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define MIN( a, b ) ( ( a < b ) ? (a) : (b) ) // Why are the parantheses imporant?
#define MAX( a, b ) ( ( a < b ) ? (b) : (a) )
#define LARGEST( a, b, c ) ( MAX( a, b ) < c ) ? c : ( MAX( a, b ) )
#define SMALLEST( a, b, c ) ( a < MIN( b, c ) ) ? a : ( MIN( b, c ) )
#define SUM( a, b, c ) ( (a + b + c) )
#define EXPR( a, b, c ) ( (LARGEST( a, b, c ) + SUM( a, b, c ) ) / SMALLEST( a, b, c ) )
int main(){
float a, b, c;
printf("Enter three integers!\n");
scanf(" %f", &a);
scanf(" %f", &b);
scanf(" %f", &c);
printf("The result is %f.\n", EXPR(a, b, c));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要查看预处理器生成的实际代码,只需执行此命令
gcc -E main.c
Run Code Online (Sandbox Code Playgroud)
我们将得到(只是最后一个命令输出的最后一部分)
#include <stdio.h>
int main()
{
float a, b, c;
printf("Enter three integers!\n");
scanf(" %f", &a);
scanf(" %f", &b);
scanf(" %f", &c);
printf("The result is %f.\n", ( (( ( ( a < b ) ? (b) : (a) ) < c ) ? c : ( ( ( a < b ) ? (b) : (a) ) ) + ( (a + b + c) ) ) / ( a < ( ( b < c ) ? (b) : (c) ) ) ? a : ( ( ( b < c ) ? (b) : (c) ) ) ));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这有点复杂
( (( ( ( a < b ) ? (b) : (a) ) < c ) ? c : ( ( ( a < b ) ? (b) : (a) ) ) + ( (a + b + c) ) ) / ( a < ( ( b < c ) ? (b) : (c) ) ) ? a : ( ( ( b < c ) ? (b) : (c) ) ) )
Run Code Online (Sandbox Code Playgroud)
我的第一个猜测就是我在评论中说的是优先权
所以让我们在/运算符中取左操作数并忽略其余的片刻以查看问题
(( ( ( a < b ) ? (b) : (a) ) < c ) ? c : ( ( ( a < b ) ? (b) : (a) ) ) + ( (a + b + c) ) )
|-----------------------------------------------|
the sum of the three operator will be added to the statement of the false condition ONLY (which is if a or b is the largest in this case) first and then we will evaluate the ?: because as you know the + is higher than ?: in table precedence
Run Code Online (Sandbox Code Playgroud)
所以让我们调用刚刚处理过的左块(左上方)LeftBlock,以便为下一次分析简化操作
因此,结合运算/符的右操作数(或整个语句中剩下的内容),我们将得到
LeftBlock / ( a < ( ( b < c ) ? (b) : (c) ) ) ? a : ( ( ( b < c ) ? (b) : (c) ) )
Run Code Online (Sandbox Code Playgroud)
现在,优先级/高于?:运算符,因此将首先计算此表达式
LeftBlock / ( a < ( ( b < c ) ? (b) : (c) ) ) ? a : ( ( ( b < c ) ? (b) : (c) ) )
|--------------------------------------------|
this is the condition for the ?: operator instead of only ( a < ( ( b < c ) ? (b) : (c) ) ) which is WRONG
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,缺少括号会导致不良后果!
还有许多其他关于宏的陷阱,你应该避免从这个链接检查它们中的一些!
最后我觉得我对这个问题进行了反混淆!:)