Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convenient function in objective-c / cocoa-touch to find a lowest number?

I have two numbers, and need to get returned the lower one. Is there any function I could use? Sure it's a easy task, I could do an if-statement. I just want to know.

like image 819
Thanks Avatar asked May 10 '09 09:05

Thanks


People also ask

How do you write blocks in Objective C?

^blockName: Always remember that the block name is preceded by the ^ symbol. The block name can be any string you like, just like you name any other variable or method. Remember that both the ^ and the block name are enclosed in parentheses ().

What is the use of block in Objective C?

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary .


2 Answers

If you're using ints, use the MIN() macro:

MIN(25, 50); //Returns 25

If you're comparing two NSNumbers, then use the compare: method:

NSNumber *number, *secondNumber; //Assume 'number'=25, 'secondNumber'=50
NSComparisonResult result = [number compare:secondNumber];

return (result==NSOrderedDescending)?secondNumber:number; //Returns the 'number' NSNumber
like image 112
Alex Rozanski Avatar answered Oct 28 '22 08:10

Alex Rozanski


The C standard library includes several min() functions that, given two numbers, will return the lower of the two:

 double fmin(double x, double y);
 long double fminl(long double x, long double y);
 float fminf(float x, float y);

To use these, just #include <math.h>.

like image 36
hbw Avatar answered Oct 28 '22 08:10

hbw