开发者

Divide int into 2 other int

开发者 https://www.devze.com 2023-03-22 16:11 出处:网络
I need to divide one int into 2 other int\'s. the first int is not constant so one problem would be, what to do with odd numbers because I only want whole numbers. For example, if int = 5, then int(2)

I need to divide one int into 2 other int's. the first int is not constant so one problem would be, what to do with odd numbers because I only want whole numbers. For example, if int = 5, then int(2) will = 开发者_如何学Go2 and int(3) will = 3. Any help will greatly be appreciated.


Supposing you want to express x = a + b, where a and b are as close to x/2 as possible:

a = ceiling(x / 2.0);
b = floor(x / 2.0);

That's pseudo code, you have to find out the actual functions for floor and ceiling from your library. Make sure the division is performed as floating point numbers.

As pure integers:

a = x / 2 + (x % 2 == 0 ? 0 : 1);
b = x / 2

(This may be a bit fishy for negative numbers, because it'll depend on the behaviour of division and modulo for negative numbers.)


You can try ceil and floor functions from math to produce results like 2 and 3 for odd inputs;

  int(2)=ceil(int/2); //will produce 3 for input 5
  int(3)=floor(int/2); //will produce 2 for input 5


Well my answer is not in Objective-C but i guess you could translate this easily. My idea is:

part1 = source_number div 2
part2 = source_number div 2 + (source_number mod 2)

This way the second number will be bigger if the starting number is an odd number.

0

精彩评论

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