我目前正在参加JavaScript课程并完成以下任务: "设计一个JavaScript程序,询问用户两个数字,然后将这两个数字作为参数发送给四个算术函数:加法,乘法,除法和模数......函数应该将值返回给调用模块,他们在哪里展示。"
<body>
<h1>Number Functions</h1>
<!-- FORM START -->
<form name="Numbers">
First number:
<br/>
<input type="number" name="number1"/>
<br/>
Second Number:
<br/>
<input type="number" name="number2"/>
<p/>
<input type="button" value="Submit" onclick="showInfo()"/>
<p/>
<textarea rows="8" colspan="150" name="info" readonly="true" value=""></textarea>
</form>
<script type="text/javascript">
function showInfo() {
// Declare and get variables
var firstNumber = parseFloat(document.Numbers.number1.value); // first number
var secondNumber = parseFloat(document.Numbers.number2.value); // second number
// Four mathematical functions
function add(num1, num2) {
var sum = num1 + " + " + num2 + " = " + (num1+num2).toFixed(2) + "\n";
return sum;
}
function multiply(num1, num2) {
var product = num1 + " \u00d7 " + num2 + " = " + (num1*num2).toFixed(2) + "\n";
return product;
}
function divide(num1, num2) {
var dividend = num1 + " / " + num2 + " = " + (num1/num2).toFixed(2) + "\n";
return dividend;
}
function modulus(num1, num2) {
var surplus = num1 + " % " + num2 + " = " + (num1%num2).toFixed(2);
return surplus;
}
var total = add(firstNumber,secondNumber) + multiply(firstNumber,secondNumber) + divide(firstNumber,secondNumber) + modulus(firstNumber,secondNumber);
document.Numbers.info.value = total;
// I need this function to get the results from the four above and put them in the textarea!
}
</script>
</body>
我不确定如何获得这四个函数的结果并显示结果,但我怀疑我的代码不起作用的原因很多是因为变量不正确放置。这是一个在线课程,教科书太可怕了!因此,如果你能指出我正确的方向(或多个正确的方向),那就太棒了。
答案 0 :(得分:0)
这有很多问题。
尝试这样的小提琴:https://jsfiddle.net/oLb1vzrb/
// Four mathematical functions
function add(num1, num2) {
return num1 + " + " + num2 + " = " + (num1 + num2).toFixed(2);
}
function multiply(num1, num2) {
return num1 + " \u00d7 " + num2 + " = " + (num1 * num2).toFixed(2);
}
function divide(num1, num2) {
return num1 + " / " + num2 + " = " + (num1 / num2).toFixed(2);
}
function modulus(num1, num2) {
return num1 + " % " + num2 + " = " + (num1 % num2).toFixed(2);
}
function showInfo() {
// Declare and get variables
var num1 = parseFloat(document.Numbers.number1.value); // first number
var num2 = parseFloat(document.Numbers.number2.value); // second number
document.Numbers.info.value = add(num1, num2) + multiply(num1, num2) + divide(num1, num2) + modulus(num1, num2);
}