views:

149

answers:

6

Hello all,

I have the following code:

float valueCalculated = (val1 / val2) * 100;

What I want to be able to do is to cap the maximum value of valueCalculated to 100.

I believe I could do this using some sort of if statement, but this would mean many more lines of code. Edit// This is not the case, see the answers below.

Thanks,

Stu

+5  A: 

You mean "many more lines of code" like this?

if (valueCalculated > 100) { valueCalculated = 100; }
Dave DeLong
That is brilliant, so simple too! I am just learning and no matter how I searched I could not find this! Thanks to all.
Stumf
This awesomeness is awesome! :D
Hilton Perantunes
A: 

I'm not an iphone dev, but isn't modulo what you're looking for?

float valueCalculated = ((val1 / val2) * 100) % 101;

?

Bartosz Wójcik
modulo would seem to work well, but if the value comes to "101", then "% 101" would make it 0. I think he just wants it capped at 100.
Dave DeLong
A: 

If you just want to limit a calculated value to 0 to 100 by "weighting" it, you would divide that value by the maximum that it could be and then multiply by 100. This assumes the value isn't negative.

gerry3
A: 
float valueCalculated = (float temp = (val1 / val2) * 100) > 100 ? 100 : temp;

but I guess a function would be better, you can do with function or a simple macro:

#define MAX(m, toset) toset = (toset > m ? m : toset)

MAX(100, valueCalculated);

I guess I understood better your question:

valueCalculated = MAX(100, (val1 / val2) * 100);

where

#define MAX(max, val) (((val) > (max)) ? (max) : (val))

hope it helps,
Joe

Jonathan
A: 

If I understand the question then...

float valueCalculated = fminf((val1 / val2) * 100, 100);

...should do what your asking.

However, are you worried about negative values, i.e. could val1 or val2 be negative and do you want to limit possible values for valueCalculated to 0-100?. If so then you might want...

float valueCalculated = fmaxf(fminf((val1 / val2) * 100, 100), 0);
Paul
A: 

What about this:

float valueCalculated = ((val1 / val2) * 100 < 100) ? (val1 / val2) * 100 : 100
dax