所以我必须制作一些代码,当用户输入1-4中的数字时,它会执行+ - *或/,具体取决于他们选择的数字。
console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");
var choice = prompt ("What is your choice?");
if (choice == 1)
{
console.log(number1 + number2);
}
if (choice == 2)
{
console.log(number1 - number2);
}
if (choice == 3)
{
console.log(number1 * number2);
}
if (choice == 4)
{
console.log(number1 / number2);
}
var number1 = prompt("Type in a number");
var number2 = prompt("Type in another number");
用户打算在选择功能后输入数字,但是当用户键入第一个数字时,会出现NaN
。
我认为这是因为用户在2个数字中甚至没有类型,但我需要用户最后输入数字。
非常感谢任何帮助和建议,谢谢
答案 0 :(得分:4)
你需要接受if else逻辑之前的数字,并将这些数字转换为int或float进行计算(默认情况下用户提示符为字符串):
console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");
var number1 = prompt("Type in a number");
var number2 = prompt("Type in another number");
number1 = parseFloat(number1);
number2 = parseFloat(number2);
var choice = prompt ("What is your choice?");
if (choice == 1)
{
console.log(number1 + number2);
}
if (choice == 2)
{
console.log(number1 - number2);
}
if (choice == 3)
{
console.log(number1 * number2);
}
if (choice == 4)
{
console.log(number1 / number2);
}

答案 1 :(得分:2)
作业没有提升,所以在你使用它们时没有定义number1和number2
答案 2 :(得分:1)
声明为全局变量。在条件之前添加提示符。数字是一个字符串output.use parseInt()
转换为整数。
如果您需要使用parseFloat()
console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");
var number1=0;
var number2=0
var choice =0;
choice = parseInt(prompt ("What is your choice?"));
number1 = parseInt(prompt("Type in a number"));
number2 = parseInt(prompt("Type in another number"));
if (choice == 1)
{
console.log(number1 + number2);
}
if (choice == 2)
{
console.log(number1 - number2);
}
if (choice == 3)
{
console.log(number1 * number2);
}
if (choice == 4)
{
console.log(number1 / number2);
}

答案 3 :(得分:0)
var x = function() {
console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");
var choice = prompt ("What is your choice?");
var number1 = Number(prompt("Type in a number"));
var number2 = Number(prompt("Type in another number"));
if (choice == 1)
{
console.log(number1 + number2);
}
if (choice == 2)
{
console.log(number1 - number2);
}
if (choice == 3)
{
console.log(number1 * number2);
}
if (choice == 4)
{
(number2 !== 0) && console.log(number1 / number2);
}
}