Javascript - 查找数字是正数还是负数
Javascript - Find if number is positive or negative
我看到了我的问题的其他解决方案,但没有一个对我有帮助。
我想创建一个函数来查找数字是正数还是负数。该函数应采用整数参数,如果整数为正数,则返回 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
、-1
或0
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。
相关文章:
- 使用全局变量来存储数字(JavaScript)
- 字符串到数字JavaScript
- 查找总和最大的数字(Javascript)
- 将字符串中的重复字符替换为不断增长的数字 [Javascript]
- 选择下拉选项时显示数字-javascript
- 用户在数字上输入金额,然后输出最高数字javascript
- 字母数字 JavaScript 正则表达式失败
- 仅数字 Javascript 表单验证
- 如何从一组特定的数字中找到最接近的更高数字:javascript
- 将字符串 num 转换为数字 JavaScript
- 将字符串转换为数字 Javascript
- 提取两种模式之间的数字 javascript
- 添加两个十六进制数字 javascript 与位移
- 确定是否按下了字母或数字-Javascript
- 可以't将字符串转换为数字javascript我的代码出了什么问题
- 按布尔值,然后按数字(javascript)对对象数组进行排序
- 正则表达式,用于获取方括号之间的字符串和数字-javascript
- If和Else比较数字JavaScript
- 检查变量是网页上的所有数字javascript
- 同时检查模为0的两个不同数字(Javascript)