无法显示消息

时间:2013-06-14 17:32:30

标签: javascript

我必须创建一个代码,要求用户输入两个数字。程序需要将两个数字相乘,然后在显示的消息中显示答案。即:5 x 7是35! (假设用户输入的数字是5和7。)

这是我现在的代码。

<title></title> 

<script type="text/javascript">
 var num1 = 0;
 var num2 = 0;
 var calculatedNum = 0;

 function calculation() {
 //create a integer variable called num2
 //Purpose: second variable
 var num2 = 0; // integer second variable

//create a integer variable called calculatedNum
 //Purpose: num1 x num2
 var calculatedNum = 0; // integer num1 x num2

//ask user '"Please type the first number"'
 //and put the answer in num1
 num1 = prompt("Please type the first number");

//ask user '"Please type the second number."'
 //and put the answer in num2
 num2 = prompt("Please type the second number.");

//Tell user: num1 + "x" + num2 + "=" + calculatedNum
 alert (num1 + "x" + num2 + "=" + calculatedNum);

} // end calculation function

}end program


</script>

3 个答案:

答案 0 :(得分:1)

你为自己过分复杂的事情。就这样做:

<script>
    var num1 = prompt('Please type the first number'),
        num2 = prompt('Please type the second number');
    alert(num1 + "x" + num2 + "=" + num1 * num2);
</script>

Demo 1

或者,如果你想将它包装在一个函数中,那么你可以从其他地方调用它:

<script>
    function calculation() {
        var num1 = prompt('Please type the first number'),
            num2 = prompt('Please type the second number');
        alert(num1 + "x" + num2 + "=" + num1 * num2);
    };
    calculation();
</script>

Demo 2

答案 1 :(得分:1)

试试吧

var num1 = 0;
var num2 = 0;
var calculatedNum = 0;

function calculation() {
    num1 = prompt("Please type the first number");
    num2 = prompt("Please type the second number.");
    calculatedNum = (num1*num2);
    alert(num1 + "x" + num2 + "=" + calculatedNum);
}

使用calculation();来调用:)

答案 2 :(得分:0)

<title></title> 

<script type="text/javascript">
 var num1 = 0;
 var num2 = 0;
 var calculatedNum = 0;

 function calculation() {
 //create a integer variable called num2
 //Purpose: second variable
 var num2 = 0; // integer second variable

//create a integer variable called calculatedNum
 //Purpose: num1 x num2
 var calculatedNum = 0; // integer num1 x num2

//ask user '"Please type the first number"'
 //and put the answer in num1
 num1 = prompt("Please type the first number");

//ask user '"Please type the second number."'
 //and put the answer in num2
 num2 = prompt("Please type the second number.");
calculatedNum = num1*num2;
//Tell user: num1 + "x" + num2 + "=" + calculatedNum
 alert (num1 + "x" + num2 + "=" + calculatedNum);

} // end calculation function


calculation();
</script>

这是按预期工作的。 你最后有一个额外的“}结束计划”。