2017-09-14 123 views
-2

我試圖打印出兩個二項式的加法。我在最後收到一條錯誤消息,我不太確定我應該怎麼做來修復它。我只是想通過添加兩個二項式來提醒用戶他們的答案。因此,如果用戶輸入1作爲a,b,c & d,則應該輸出'2 + 2i'。我的主要目標是找出如何正確輸出數學,但如果任何人有任何提示如何更有效地連接變量,這將是有益的。Javascript alert()with string concatenation

This program takes in four numbers as input from a user, and uses those inputs as a,b,c & d to solve four different calculations */ 

var a1 = prompt("Enter a positive whole number for 'a'"); 
var b1 = prompt("Enter a positive whole number for 'b'"); 
var c1 = prompt("Enter a positive whole number for 'c'"); 
var d1 = prompt("Enter a positive whole number for 'd'"); 

var a = parseInt(a1); // These four lines convert input from string to int 
var b = parseInt(b1); 
var c = parseInt(c1); 
var d = parseInt(d1); 

aPlusC = (a + c); 
bPlusD = (b + d); 
bPlusDFinal = bPlusD + "i"; 

var calc1 = aPlusC + "+ " bPlusDFinal; 
alert(calc1); 
+2

嘗試閱讀錯誤。 – SLaks

+3

閱讀錯誤信息並指出生產線會是一個好的開始。 – David

+0

您在字符串和標識符之間缺少運算符。 – Xufox

回答

0
var a1 = prompt("Enter a positive whole number for 'a'"); 
var b1 = prompt("Enter a positive whole number for 'b'"); 
var c1 = prompt("Enter a positive whole number for 'c'"); 
var d1 = prompt("Enter a positive whole number for 'd'"); 

var a = parseInt(a1); // These four lines convert input from string to int 
var b = parseInt(b1); 
var c = parseInt(c1); 
var d = parseInt(d1); 

aPlusC = (a + c); 
bPlusD = (b + d); 
bPlusDFinal = bPlusD + "i"; 

var calc1 = aPlusC + "+ " + bPlusDFinal; // you missed "+" before bPlusDFinal 

alert(calc1); 
+0

您可以將基數添加到['parseInt'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt),如果採用前導零號碼,那麼它防止被解釋爲八進制數。 –

0

嘗試下面的代碼。

var a1 = prompt("Enter a positive whole number for 'a'"); 
var b1 = prompt("Enter a positive whole number for 'b'"); 
var c1 = prompt("Enter a positive whole number for 'c'"); 
var d1 = prompt("Enter a positive whole number for 'd'"); 

var a = parseInt(a1); // These four lines convert input from string to int 
var b = parseInt(b1); 
var c = parseInt(c1); 
var d = parseInt(d1); 

aPlusC = (a + c); 
bPlusD = (b + d); 
bPlusDFinal = bPlusD + "i"; 
bPlusDFinal = "+" + bPlusDFinal 
var calc1 = aPlusC + bPlusDFinal; 
alert(calc1);