将整数分成两个(几乎)相等的部分 [英] Separate an integer into two (nearly) equal parts

查看:154
本文介绍了将整数分成两个(几乎)相等的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个整数分成两个数字。有点像除以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.

这篇关于将整数分成两个(几乎)相等的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆