Separate an integer into two (nearly) equal parts

后端 未结 11 916
囚心锁ツ
囚心锁ツ 2020-12-06 04:09

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         


        
11条回答
  •  日久生厌
    2020-12-06 04:44

    Your code can be simplified a bit:

    var num = 7;
    var p1 = Math.floor(num / 2);
    var p2 = p1;
    
    if (num % 2 != 0) {
       p1++;
    }
    console.log(p1, p2);

提交回复
热议问题