I have the following calculation to make:
float value = MY_VALUE;
float percentage = (value - MIN)/(MAX - MIN);
if (percentage < 0)
percentage = 0;
if (percentage > 1)
percentage = 1
I was just wondering if there is some method that exists in Objective-C or C to help accomplish this, like for example a method that will round the "value" float to be between the MIN and MAX bounds.
There is no such method in standard C libraries (I don't know about Objective C).
No.
On another note, you should probably update your code so you are preventing a possible divide-by-zero:
float den = (value - MIN);
float num = (MAX - MIN);
float percentage;
if(den) {
percentage = num / den;
if (percentage < 0.0f ) {
percentage = 0.0f;
} else if (percentage > 1.0f) {
percentage = 1.0f;
} else {
printf("Percentage: %3.2f",percentage);
}
} else {
percentage = 0.0f;
printf("DIVIDE BY ZERO ERROR!");
}
Also, careful. Oracle is suing Google over a very similar piece of code. You may want to reconsider posting it publicly:
http://developers.slashdot.org/story/12/05/16/1612228/judge-to-oracle-a-high-schooler-could-write-rangecheck
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With