简体   繁体   中英

New to programming, can't figure out why this factor calculator doesn't work

I'm trying to make a factor calculator. You input a number, and it finds out the factors of that number. If you divide the original number by its factor you get zero, and I'm trying to implement that here so that when it returns with '0' it gets pushed to an array and that array is printed.

 var number = prompt("Number?") var array = [] function modulo(a, b) { return a % b; } for (counter = 0; counter < number; counter++) { var result = modulo(number, counter) if (result = 0) { array.push(counter) } } for (counter = 0; counter < array.length; counter++) { alert(array[counter]) } 

What happens is the prompt shows up, I input a number, and nothing happens. Can anybody help?

Here is the problem, you have used = (Assignment operator) instead of == comparison operator

for (counter = 0; counter < number; counter++)
{
    var result = modulo(number, counter)
    if (result == 0) // in your code this is result = 0
    {
        array.push(counter)
    }
}

Working demo


Complete code:

var number = prompt("Number?")
var array = []
function modulo(a, b)
{
    return a % b
}
for (counter = 0; counter < number; counter++)
{
    var result = modulo(number, counter)
    if (result == 0)
    {
        array.push(counter)
    }
}

for (counter = 0; counter < array.length; counter++)
{
    alert(array[counter])
}

要检查值是否相等,请使用==而不是=

if (result == 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM