【问题标题】:Trying to add three numbers in javascript using functions but its not adding them instead it just writes them as one number尝试使用函数在javascript中添加三个数字,但它不添加它们,而是将它们写为一个数字
【发布时间】:2023-03-09 06:00:01
【问题描述】:

尝试使用函数在 javascript 中添加三个数字,但它不添加它们,而是将它们写为一个数字

function numinput(a,b,c,res){
a = prompt("Enter first number");
    b = prompt("Enter second number");
    c =  prompt("Enter third number");

    res = a + b + c ;
    alert (res);
}  

numinput();

【问题讨论】:

标签: javascript function addition


【解决方案1】:

使用

将值转换为数字

parseInt

。这是一个可行的解决方案。

function numinput(a,b,c,res){
        a = parseInt(prompt("Enter first number"), 10);
        b = parseInt(prompt("Enter second number"), 10);
        c = parseInt(prompt("Enter third number"), 10);

        res = a + b + c ;
        alert (res);
    }

    numinput();

【讨论】:

  • 这是正确答案。虽然您可以在每个变量前面使用一元运算符 +,但 parseInt(var, radix) 在人类易读性方面更加明确。
  • @KyleRichardson 是的,有 + 将通过强制完成这项工作,但感谢输入伙伴!
【解决方案2】:

prompt 返回一个string。您需要先将字符串转换为数字,否则您将连接字符串:'5' + '7' === '57'

以下是实现此目的的一些方法:

1 - 使用Number

Number('5');

2 - 使用parseIntparseFloat

parseInt('20', 10);
parseFloat('5.5');

3 - 一元 + 运算符作为其他答案解释

+'5'

工作演示:

function numinput() {
    var a = prompt("Enter first number"),
        b = prompt("Enter second number"),
        c = prompt("Enter third number"),
        res = Number(a) + Number(b) + Number(c);
      
    alert(res);
}

numinput();

【讨论】:

    【解决方案3】:

    每个用户条目是typeof string,它被连接成一个整体string。如果要将每个元素添加为 Math 操作,请将条目解析为数字,在变量前使用 + 符号或使用 parseInt 函数对其进行解析。

    function numinput(a, b, c, res) {
      a = prompt("Enter first number");
      b = prompt("Enter second number");
      c = prompt("Enter third number");
    
      res = +a + +b + +c;
      alert(res);
    }
    
    numinput();

    【讨论】:

    • 一元+运算符。这些天我没有看到很多人使用它。 :)
    【解决方案4】:

    您需要将每个值(即字符串)转换为带有一元 + 的数字。

    然后我建议将变量声明移到函数中而不是函数的参数内部,因为您不需要它们,而是在函数内部分配值。

    function numinput() {
        var a = +prompt("Enter first number"),
            b = +prompt("Enter second number"),
            c = +prompt("Enter third number"),
            res = a + b + c;
          
        alert(res);
    }
    
    numinput();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      相关资源
      最近更新 更多