简体   繁体   中英

Javascript - Find if number is positive or negative

I see other solutions to my question but none that help me.

I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.

Also, prompt the user again and again if anything other than a number is entered

Here's the code so far

When I enter a number, it keeps alerting me it is true or false but won't let me enter another. How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1

function isPositive(num) {

    var result;

    if (num >= 0) {
        result = true;
    } else if (num < 0) {
        result = false;
    }
    return result;
}

var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
    alert(isPositive(num));

    if (isNaN(num)) {
        alert("No number entered. Try again");
        num = parseInt(prompt("Enter a number"));
        isPositive(num);
        while (num != -1) {
            alert(isPositive(num));
        }
    }
}

There's a few things wrong with your code, so here's a rewrite with comments:

 function isPositive(num) { // if something is true return true; else return false is redundant. return num >= 0; } // when you want to keep doing something until a condition is met, // particularly with user input, consider a while(true) loop: var num; while (true) { num = prompt("Enter a number"); // check for null here if (num === null) { alert("No number entered. Try again."); continue; // return to the start of the loop } num = parseInt(num, 10); // second argument is NOT optional if (isNaN(num)) { alert("Invalid number entered. Try again."); continue; } // once we have a valid result... break; } // the loop will continue forever until the `break` is reached. Once here... alert(isPositive(num)); 

The number 0 is neither positive, nor negative! :P

function isPositive(num)
{
    if(num < 0)
        return false;
    else
        return true;
}

Or a simple way,

function isPositive(num)
{
    return (num > 0);
}

You are testing if it isn't -1. Try this:

if(num < 0){
...IS NEGATIVE...
}else{
...IS POSITIVE...
}

This checks if it is less than or greater than 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