Divide int's and round up in Objective-C

前端 未结 5 840
既然无缘
既然无缘 2021-01-31 01:11

I have 2 int\'s. How do I divide one by the other and then round up afterwards?

相关标签:
5条回答
  • 2021-01-31 01:43
    -(NSInteger)divideAndRoundUp:(NSInteger)a with:(NSInteger)b
    {
      if( a % b != 0 )
      {
        return a / b + 1;
      }
      return a / b;
    }
    
    0 讨论(0)
  • 2021-01-31 01:43

    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 讨论(0)
  • 2021-01-31 01:46

    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
    
    0 讨论(0)
  • 2021-01-31 01:46

    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
    
    0 讨论(0)
  • 2021-01-31 02:08

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

    0 讨论(0)
提交回复
热议问题