简体   繁体   中英

Return zero or positive number?

I was initially thinking that the code below would return 0, my question, is there a function that I can use to only receive zero/positive results here?

NSUInteger pruneSize = 5 - 20; // Returns: -15

Currently I am just checking the result myself, but was wondering if I was missing something simpler.

NSUInteger pruneSize = 5 - 20;
if(pruneSize >= 0) {
    // Do zero/positive Stuff ...
}

pruneSize >= 0 is always true as pruneSize is unsigned. You should get a warning here. You need to change the type to NSInteger , that is the signed integer. If you want to clip the lower value to zero for a signed int then you can do this:

NSInteger pruneSize = 5 - 20; // signed int
pruneSize = pruneSize < 0 ? 0 : pruneSize;

You can use abs(pruneSize) which will return you positive or zero number in any case.

EDIT:

NSUInteger pruneSize = 5-20;
if(pruneSize < 0)
{
     pruneSize = 0;
}
NSLog(@"%d",pruneSize);

Hope this helps you.

If you want your function to return always zero if your result is in negative(less than 0) then return zero or else return result

int n=0;
if(result > 0){ //positive
   n = result
else
   n = 0
return n

or use the abs method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM