C中的最大值和最小值是多少#定义函数

What are the MAX and MIN in C? #define function

本文关键字:多少 定义 函数 最小值 最大值      更新时间:2023-10-16

我是一名学生,我的老师给了我一个已经解决的学习练习,在他的练习中我看到了这行:

 #define MIN(a,b) ((a) < (b) ? (a) : (b))

我以前从未使用过#define。

我不明白什么:

((a) < (b) ? (a) : (b))

代表。

看起来像是"?"是一个不确定的比较器。有人能帮我吗?

它被称为条件运算符(或三元运算符(

#define MIN(a,b) ((a) < (b) ? (a) : (b))

平均值:

if ((a) < (b)){   
  return a;  
} else {   
  return b; 
}

所以如果你愿意的话:

int test = MIN(5,10);

测试将是5

链接到wiki页面时出现问题:http://goo.gl/bw2sL

#define定义了一个新的预处理器宏,在本例中,它将MIN代码放在您放置它的位置;ab的"变量"将替换为您作为输入提供给宏的任何变量。

 #define MIN(a,b) ((a) < (b) ? (a) : (b))
 MIN(5,6);
 //gets expanded to
 ((5) < (6) ? (5) : (6))

实际的表达式是使用三元运算符,根据表达式的求值结果返回A或B,您可以在这里阅读更多信息:

http://en.cppreference.com/w/cpp/language/operator_other

最后,当你用c++标记你的问题时,请考虑非宏的max和min函数。

#include <algorithm>
...
int i=std::min(5,6);