Javascript - 查找数字是正数还是负数

时间:2014-12-04 13:11:44

标签: javascript

我看到了我的问题的其他解决方案,但没有一个可以帮助我。

我想创建一个函数来查找数字是正数还是负数。该函数应采用整数参数,如果整数为正则返回true,如果为负则返回false。

此外,如果输入的数字不是

,则会一次又一次地提示用户

这是迄今为止的代码

当我输入一个号码时,它会一直警告我这是真是假,但不会让我进入另一个号码。 如何控制循环,以便在输入-1之前询问?它没有让我有机会进入-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));
        }
    }
}

4 个答案:

答案 0 :(得分:3)

你的代码有一些问题,所以这里是一个带注释的重写:

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));

答案 1 :(得分:2)

数字0既不是正面的,也不是负面的! :P

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

或者简单的方法,

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

答案 2 :(得分:0)

您正在测试不是 -1。试试这个:

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

检查它是否小于或大于0.

答案 3 :(得分:0)

相关问题