Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for calculating percentage for a value between two bounds

Tags:

c

ios

objective-c

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.

like image 300
Darren Avatar asked Dec 22 '25 23:12

Darren


2 Answers

There is no such method in standard C libraries (I don't know about Objective C).

like image 132
Oliver Charlesworth Avatar answered Dec 24 '25 12:12

Oliver Charlesworth


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

like image 39
Cloud Avatar answered Dec 24 '25 13:12

Cloud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!