How do I use Min & Max?! HELP ME PLEASE!

Posted By: Anonymous

How do I use Min & Max?! HELP ME PLEASE! - 03/25/02 08:07

How can I limit a variable using these functions?
Help Please!

Glome
Posted By: Anonymous

Re: How do I use Min & Max?! HELP ME PLEASE! - 03/25/02 19:43

result=min(10, 20); will use always the smaller value 10
result=max(10,20); will use 20 insted

you can combine that to:
result=max(0, min(20,10)); first it will chose the min of (20,10) =10 and then it will chose the maximum of (0,10) =10 result=10;
Posted By: Anonymous

Re: How do I use Min & Max?! HELP ME PLEASE! - 03/26/02 02:49

Um, that's a little confusing. Could you explain it to me a little more please?

Glome
Posted By: Phantom88

Re: How do I use Min & Max?! HELP ME PLEASE! - 03/26/02 03:00

result=max(0, min(result,10)); Now result is limited to 1-10.

~Phantom88~
Posted By: Anonymous

Re: How do I use Min & Max?! HELP ME PLEASE! - 03/26/02 03:11

Ok, thanks!
Posted By: Anonymous

Re: How do I use Min & Max?! HELP ME PLEASE! - 03/26/02 03:23

"min" compares two variables (numbers) and will return whichever one is smaller (the minimum).

thing = min(noise, 10);

If noise is 11, thing will be 10 (it's smaller)
If noise is 9, thing will be 9 (it's smaller)

"max" works the opposite way:

thing = max(noise, 10);

If noise is 11, thing will be 11 (it's bigger)
If noise is 9, thing will be 10 (it's bigger)

min sets the upper limit for the value of a variable.
max sets the lower limit for the value of a variable.

Suppose you have a tachometer, and as long as the engine is running, you want to show the RPM of the engine. But you don't want it to go below 500 RPM (idle) even when you are backing up. (Negative speed could result in a negative RPM calculation.) Or, if you are stopped (car speed is zero), but the engine is still running, your calculations could result in a zero engine speed.
The solution is very simple:
RPM = max(RPM,500);

The RPM will then be whichever is bigger, the actual RPM, or 500. So even if the real RPM goes below idle, to zero, or even negative, your tachometer will never show below 500.
(You will need to force it to zero somewhere else in your code, if you do shut off the engine.)

The example in the manual is just a tricky combination of the two. The second variable has been replaced by substituting the other min/max function. (Pick some numbers, and work through it by hand, to understand it better. Start with the embedded function.)

One gotcha - the manual is missing the last parenthesis, on the right. If you use the example, exactly as it is, you will get an error. Just add the missing right parenthesis, and it will work fine!

Hope this helps!
Posted By: Anonymous

Re: How do I use Min & Max?! HELP ME PLEASE! - 04/04/02 14:28

Thanks!

Glome [Big Grin]
© 2023 lite-C Forums