2017-04-22 53 views
0

嘗試使用功能,在JavaScript中添加三個數字,但它不是增加他們,而不是它只是寫他們作爲一個數量嘗試使用功能,在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(); 
+0

的可能的複製[使用Javascript級聯數字,而不是增加了( HTTP://計算器。com/questions/14656003/javascript-concatenating-numbers-not-add-up) – legoscia

回答

2

使用

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();

+0

這是正確的答案。儘管你可以在每個變量前面使用一元運算符+,但parseInt(var,radix)在人類可讀性方面更加明確。 –

+0

@KyleRichardson Yup有+會通過強制來完成這項工作,但是感謝輸入伴侶! – HenryDev

0

的每個用戶條目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();

+1

用於一元+運算符。這些天我沒有看到很多人在使用它。 :) – Tushar

0

您需要的每一個值,它是一個字符串轉換,爲數字與一元+

然後我建議將變量聲明移動到函數中,而不是在函數的參數中,因爲您不需要它們,並且可以在函數內分配值。

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();

1

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();

相關問題