javascript 我似乎无法将小数从数组中删除

91zkwejq  于 2022-11-20  发布在  Java
关注(0)|答案(2)|浏览(141)

这可能是非常基本的,但我的代码似乎有一些错误或期望,可能不适合我。一些背景信息:我的代码是这样创建的,它要求用户输入一个整数,然后分析用户的输入,并向用户显示一个数字的输出,这些数字相乘后等于用户的输入。

期望值

输入:7输出(在控制台中):(1,7)(7,1)。
但相反,我的代码也输入与用户输入相等的小数。
"现实“
输入:7输出:(1.1666666666666667,6)、(1.4,5)、(1.75,4)、(2.33333333333333335,3)、(3.5,2)、(7,1)、(无穷大,0)。

var numInput= parseInt(prompt("Please enter a number larger than 1"));
        //This asks the user for the input 
    var valueArray = [];//This is the empty array we are going to use in the further code. 
            if(numInput <= 0 || numInput <= 1) {
                 console.log("Goodbye!")
        }//This line is an if loop which if the user inputs 0 or 1 then the code will end. 
   
        while(numInput > 0) {// This while loop is there so that the user can input as many numbers he wants 
         var valueArray = [];//Now the numbers are inside this empty array
         var numInput = parseInt(prompt("Please enter a number larger than 1"));
   
         for (var iterator = 0; iterator < numInput; ++iterator) {//This for loop is the calculation, for when a = 1, the a has a greater value then 
           var valueSubtracted = numInput / iterator //This is where the variable subtracts the orignal value n so that we have something along the lines of (1,6) instead (1,7)
           valueArray.unshift(valueSubtracted + ", " + iterator ); //This just moves the answers into a concantination, and moves into the array
           }
        
     
        console.log("The additive combinations are: " + "(" + valueArray.join("), (") + "). ");
       }

我真正想要的只是去掉小数和与之相关的数字。例如:
输入:7输出:***(1.166666666666667,6)***、***(1.4,5)、******(1.75,4)、******(2.3333333333333333335,3)***、***(3.5,2)、***(7,1)、***(无限大,0)。***
上面注意到:粗体和斜体部分应该从数组中删除。This is what it looks like in the console.

mqkwyuun

mqkwyuun1#

你应该检查它是否能被整数整除。要做到这一点,使用n % m === 0并在if-子句中检查它。它应该在for-循环中创建。另外:执行零除法不会导致错误。相反,它返回Infinity。考虑在for-循环中将start值更改为1以避免这种情况。

uyhoqukh

uyhoqukh2#

在你的代码中有很多需要改进/更正的地方,但是我只会把重点放在让它像你希望的那样工作上。只需要修改下面的行:

var valueSubtracted = ((numInput / iterator) % 1 === 0) ? (numInput / iterator) : Infinity 
// check if valueSubtracted is an N group number or else set it as Infinity

if(isFinite(valueSubtracted)) valueArray.unshift(valueSubtracted + ", " + iterator )
// only add to array if finite number

而且,numInput<=1已经是nimInput<=0了,为什么还要两者都有呢?

相关问题