将整数分成两个(几乎)相等的部分

编程入门 行业动态 更新时间:2024-10-23 23:22:07
本文介绍了将整数分成两个(几乎)相等的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要将一个整数分成两个数字。有点像除以2但我只想要整数组件,例如:

I need to separate an integer into two numbers. Something like dividing by two but I only want integer components as a result, such as:

6 = 3 and 3 7 = 4 and 3

我尝试了以下内容,但我不确定它是最佳解决方案。

I tried the following, but I'm not sure its the best solution.

var number = 7; var part1 = 0; var part2 = 0; if((number % 2) == 0) { part1 = number / 2; part2 = number / 2; } else { part1 = parseInt((number / 2) + 1); part2 = parseInt(number / 2); }

这就是我想要的,但我认为这段代码不干净。

This does what I want, but I don't think this code is clean.

有更好的方法吗?

推荐答案

找到第一部分并从原始数字中减去它。

Just find the first part and subtract it from the original number.

var x = 7; var p1 = Math.floor(x / 2); var p2 = x - p1; console.log(p1, p2);

如果 x 为奇数, p1 将收到两个加数中较小的一个。您可以通过调用 Math.ceil 来切换它。

In the case of x being odd, p1 will receive the smaller of the two addends. You can switch this around by calling Math.ceil instead.

更多推荐

将整数分成两个(几乎)相等的部分

本文发布于:2023-11-26 00:43:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631978.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!