-1

我必须创建一个要求用户输入两个数字的代码。程序需要将这两个数字相乘,然后在显示的消息中显示答案。即: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>
4

3 回答 3

1

你为自己把事情复杂化了。只需这样做:

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

演示 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>

演示 2

于 2013-06-14T17:38:44.767 回答
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();打电话:)

于 2013-06-14T17:40:13.540 回答
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>

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

于 2013-06-14T17:41:33.350 回答