我需要将一个整数分成两个数字。像是除以2之类的东西,但我只想要整数分量,例如:
6 = 3 and 3
7 = 4 and 3
我尝试了以下内容,但我不确定它是最佳解决方案。
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);
}
这就是我想要的,但我不认为这段代码是干净的。
有更好的方法吗?
答案 0 :(得分:107)
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);
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.
答案 1 :(得分:38)
让javascript为你做Math。
var x = 7;
var p1 = Math.ceil(x / 2);
var p2 = Math.floor(x / 2);
console.log(p1, p2);
答案 2 :(得分:8)
您的代码可以简化一下:
var num = 7;
var p1 = Math.floor(num / 2);
var p2 = p1;
if (num % 2 != 0) {
p1++;
}
console.log(p1, p2);
答案 3 :(得分:6)
var num = 7;
var part1 = parseInt(num/2);
var part2 = num - part1;
console.log(part1, part2);

答案 4 :(得分:4)
另一种方法是使用按位运算符。它不适用于非常大的数字
function splitter(number){
part1 = (number>>1) + (number&1);
part2 = number>>1;
console.log(number + ":", part1 + "+" + part2);
}
splitter(7);
splitter(6);
splitter(2**30+1); // Breaks for values greater than 2**31
splitter(2**31+1);

答案 5 :(得分:3)
var x = 11;
var a = Math.ceil(x/2);
var b = x-a;
console.log("x = " + x + " , a = " + a + " , b = " + b);

答案 6 :(得分:1)
如果您不希望输出为consecutive或完全相同,但又希望'将整数分成两个数字,这就是您的解决方案:
function printSeparatedInts(num) {
let smallerNum = Math.floor(Math.random() * Math.floor(num));
if (num && smallerNum === (num/2)) { // checking if input != 0 & output is not consecutive
printSeparatedInts(num)
} else {
console.log(smallerNum, (num - smallerNum))
}
}
printSeparatedInts(22)
printSeparatedInts(22) // will likely print different output from above
printSeparatedInts(7)
答案 7 :(得分:0)
我自豪地向你展示了一个发电机对象!
初始化它并使用它! 它会每隔一次使用自动更改值,即使在同一行!!
用法:a = new splitter(n)
然后console.log(a+" and "+a)
function splitter(n){
this.p1 = Math.floor(n/2);
this.p2 = n-this.p1;
this.cnt=0;
this.valueOf= ()=> (++this.cnt%2)? this.p1:this.p2;
return n;
}
a = new splitter(5);
console.log(a + " and " +a);
console.log(a + " and " +a);
console.log(a + " and " +a);
b = new splitter(11);
console.log(b + " and " +b);

答案 8 :(得分:0)
var number = 7;
var part1 = 0;
var part2 = 0;
if(number == 0) {
part1 = (part2 = 0);
console.log(part1, part2);
}
else if(number == 1) {
part1 = 1;
part2 = 0;
console.log(part1, part2);
}
else if((number % 2) == 0) {
part1 = part2 = number / 2;
console.log(part1, part2);
}
else {
part1 = (number + 1) / 2;
part2 = number - part1;
console.log(part1, part2);
}
只有其他解决方案,我认为表现还可以。
答案 9 :(得分:-2)
或者这样:)
, and
答案 10 :(得分:-3)
var n = 7;
var p1 = (n - (n % 2)) / 2;
var p2 = (n + (n % 2)) / 2;
console.log(p1, p2);