Develop an algorithm and write the JavaScript that allows a student to enter two
ID: 3543753 • Letter: D
Question
Develop an algorithm and write the JavaScript that allows a student to enter two numbers
- then ask the user if they want to add, subtract, multiply, or divide the two numbers.
Prompt the user to enter a 1 to add, 2 to subtract, 3 to mulitply, or 4 to divide.
If a number other 1, 2, 3, or 4 is entered then print an error message and exit the program.
If a correct number is entered print the two numbers and the aritmetic result.
Then aks the user if they want to perform another set of arithemtic -
if the user responds Y or y (for yes ) then loop back up, enter two new numbers, and
a new operation. Continue till the user enters a N or n to indicate that they do not want
to any more arithmetic calculations to be performed.
I have to write this in notepad and save it as html,i also can't use any advanced code
only basic ones..i've attached a sample format that has to be used below...Thank you!
https://media.cheggcdn.com/media/28a/28a2062a-b993-480d-b7d2-7e82200715c0/phpAthNRm.png
Explanation / Answer
<html>
<head>
</head>
<body>
<script>
var num1 = 0, num2 = 0;
var result;
var operator;
var choose;
do
{
num1 = window.prompt("Enter the first number");
num2 = window.prompt("Enter the second number");
operator = window.prompt("Enter 1 for Add, 2 for Substract, 3 to Multiply, 4 to Divide");
if(operator == 1)
{
result = parseInt(num1) + parseInt(num2);
operator = "+";
}
else if (operator == 2)
{
result = parseInt(num1) - parseInt(num2);
operator = "-";
}
else if (operator == 3)
{
result = parseInt(num1) * parseInt(num2);
operator = "*";
}
else if (operator == 4)
{
result = parseInt(num1) / parseInt(num2);
operator = "/";
}
else
{
alert("Error input!");
choose = "N";
}
alert(num1 + " " + operator + " " + num2 + " = " + result);
choose = window.prompt("Do you want to repeat? (Y/N)");
choose = choose.toUpperCase();
} while (choose == "Y")
</script>
</body>
</html>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.