Find the larger of two numbers using the max() function.
Use the following function to compare two numbers and find the larger:
max(x, y)
The function admits the following parameters:
x: the first number to compare. Allowed data types: any data type.y: the second number to compare. Allowed data types: any data type.This function returns the larger of the two parameter values compared.
Compares a and b and print the larger variable in the Serial Monitor.
int a = 25;
int b = 14;
void setup() {
Serial.begin(9600);
int max = max(a, b);
Serial.print("The larger value is: ");
Serial.println(max);
}
void loop() {
}
Another typical application could be to constrain a minimum value of a variable, as shown in the following example:
sensVal = max(sensVal, 20); // assigns sensVal to the larger of sensVal or 20
// (effectively ensuring that it is at least 20)
Perhaps counter-intuitively, max() is often used to constrain the lower end of a variable’s range, while min() is used to constrain the upper end of the range.
Because of the way the max() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results
max(a--, 0); // avoid this - yields incorrect results
// use this instead:
max(a, 0);
a--; // keep other math outside the function