将 int 分成另外 2 个 int

发布于 2024-11-26 01:16:19 字数 113 浏览 1 评论 0原文

我需要将一个整数分成另外两个整数。第一个 int 不是常量,所以一个问题是,如何处理奇数,因为我只想要整数。例如,如果 int = 5,则 int(2) 将 = 2,int(3) 将 = 3。任何帮助将不胜感激。

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 = 2 and int(3) will = 3. Any help will greatly be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

过气美图社 2024-12-03 01:16:19

假设您想表达 x = a + b,其中 abx/2 非常接近尽可能:

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

这是伪代码,您必须从库中找出地板和天花板的实际功能。确保除法以浮点数执行。

作为纯整数:(

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

对于负数来说这可能有点可疑,因为它取决于负数的除法和取模的行为。)

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.)

你好,陌生人 2024-12-03 01:16:19

您可以尝试使用数学中的 ceil 和 Floor 函数来生成奇数输入的结果,例如 2 和 3;

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

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
吃→可爱长大的 2024-12-03 01:16:19

好吧,我的答案不是用 Objective-C 写的,但我想你可以很容易地翻译它。
我的想法是:

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

这样如果起始数字是奇数,第二个数字就会更大。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文