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

Javascript - Find if number is positive or negative

本文关键字:数字 Javascript 查找      更新时间:2023-09-26

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

我想创建一个函数来查找数字是正数还是负数。该函数应采用整数参数,如果整数为正数,则返回 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));
        }
    }
}

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

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

Math.sign(number)

返回1-10

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

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

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

或者一个简单的方法,

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

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

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

这将检查它是否小于或大于 0。