开发者

Return zero or positive number?

开发者 https://www.devze.com 2023-03-24 07:22 出处:网络
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?

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(prun开发者_JS百科eSize >= 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号