开发者

Divide int's and round up in Objective-C

I have 2 int's. How do I divide one by the other and then round up afterwa开发者_运维百科rds?


If your ints are A and B and you want to have ceil(A/B) just calculate (A+B-1)/B.


What about:

float A,B; // this variables have to be floats!
int result = floor(A/B); // rounded down
int result = ceil(A/B); // rounded up


-(NSInteger)divideAndRoundUp:(NSInteger)a with:(NSInteger)b
{
  if( a % b != 0 )
  {
    return a / b + 1;
  }
  return a / b;
}


As in C, you can cast both to float and then round the result using a rounding function that takes a float as input.

int a = 1;
int b = 2;

float result = (float)a / (float)b;

int rounded = (int)(result+0.5f);
i


If you looking for 2.1 roundup> 3

double row = _datas.count / 3;
double rounded = ceil(_datas.count / 3);
if(row > rounded){
    row += 1;
}else{

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜