添加公式无效的javascript代码

时间:2014-05-16 16:51:59

标签: javascript jquery html

我有用html和javascript编写的代码。它的作用是使用提示生成正数和负数,然后将使用公式n *(n + 1)/ 2生成的所有数字相加。代码似乎不能很好地工作,因为在使用公式和用户输入查找总和时,我得到了错误的值。我的代码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

    <script language="javascript">

        var countpos = 1;
        var countneg = 0;       

        function pos(){
            var positive = prompt("enter limit for positive numbers");
            document.write(positive*(positive+1)/2 +"<br>");            

            while(countpos <= positive){
                document.write(" " + countpos);
                document.write("<br>");
                countpos++;
            }                                       
        }

        function neg(){
            var negative = prompt("enter limit for negative numbers");
            while(countneg >= negative){
                document.write(" " + countneg);
                document.write("<br>");
                countneg--;
            }
        }

    </script>
</head>

<body>

    What do you want to output? Positive or Negative numbers? <br>
    <input type="button" value="positive numbers" onClick="pos()"> <br>
    <input type="button" value="negative numbers" onClick="neg()">

</body>
</html>

3 个答案:

答案 0 :(得分:0)

var positive = prompt("enter limit for positive numbers");
console.log(typeof positive);

这是一个字符串,而不是一个数字,你需要用parseInt或parseFloat转换它

var positive = parseInt(prompt("enter limit for positive numbers"), 10);

var entry = prompt("enter limit for positive numbers");
var positive = parseInt(entry, 10);
if ( isNaN(positive) ) {
    //error message
}

答案 1 :(得分:0)

它将它们视为字符串。将代码更改为此将显示原因......

    var positive = prompt("enter limit for positive numbers");
    alert(positive);
    alert(positive+1);

试试这个..

 document.write(positive*(Number(positive)+1)/2 +"<br>"); 

答案 2 :(得分:0)

正如adeneo所说,document.write将覆盖文档上的文本。 试试这个:

    var countpos = 1;
    var countneg = 0;       

    function pos(){
        var positive = prompt("enter limit for positive numbers");
        var str = '';
        str += (positive*(positive+1)/2 +"<br>");            

        while(countpos <= positive){
            str += (" " + countpos);
            str += ("<br>");
            countpos++;
        }                        

        document.write(str);
    }

    function neg(){
        var negative = prompt("enter limit for negative numbers");
        while(countneg >= negative){
            str += (" " + countneg);
            str += ("<br>");
            countneg--;
        }
        document.write(str);
    }

这将一次只能运行一个功能,但我现在已经给你了解下一步就是你如何利用它。