CC.
CC.

Reputation: 803

Find the smallest value among variables?

I have from 4 up to 20 variables that differ in size. They are all of type float and number values. Is there an easy way to find the smallest value among them and assign it to a variable? Thanks

Upvotes: 0

Views: 4650

Answers (4)

CC.
CC.

Reputation: 803

Thanks for all your answers and comments.. I learn a lot from you guys :)

I ended up using something like Martin suggested.

if (segmentValueNumber == 11){

    float min = 100000000;      


        if(game51 > 0, game51 < min){
            min=game51;
        }

        if(game52 > 0, game52 < min){
            min=game52;
        }
}

...............................................

I could not figure out how to implement it all into one array since each result depends on a segment control, and I think the program is more optimised this way since it only checks relevant variables.

But thanks again, you are most helpful..

Upvotes: -1

Marco
Marco

Reputation: 779

The best solution, without foreach.

`- (float)minFromArray:(float *)array size:(int)arrSize

{

float min;
int i;

min = array[0]
for(i=1;i<arrSize;i++)
    if(array[i] < min)
        min = array[i];
return min;

} `

If you want to be sure, add a check of the arrSize > 0.

Marco

Upvotes: 0

Martin Janiczek
Martin Janiczek

Reputation: 3035

I agree with Davy8 - you could try rewriting his code into Objective C.

But, I have found some min()-like code - in Objective C!

Look at this:

- (int) smallestOf: (int) a andOf: (int) b andOf: (int) c
{
     int min = a;
     if ( b < min )
         min = b;

     if( c < min )
         min = c;

     return min;
}

This code assumes it'll always compare only three variables, but I guess that's something you can deal with ;)

Upvotes: 1

David Ly
David Ly

Reputation: 31586

Not sure about objective-c but the procedure's something like:

float min = arrayofvalues[0];
foreach( float value in arrayofvalues)
{
    if(value < min)
        min=value;
}

Upvotes: 8

Related Questions