[英]Calculating the Sum of Squares in Javascript
我在計算javascript中的平方和時遇到問題。 當我為循環和變量索引定義時,我迷路了。 誰能幫助我了解我在做什么錯?
var sums = [];
var sumsqs= Number(prompt("Please enter a number to sum the square"));
for (var index = 0; index < sumsqs.length; index++) {
var total = total + sumsqs[index] * sumsqs[index];
document.write("<h1>The sum of squares is " + total + ".</h1>");
謝謝,Viv
例如,如果您想將逗號分隔的數字列表轉換為數字數組,那不是
Number(prompt("Please enter a number to sum the square"))
(它將嘗試將整個字符串轉換為數字),而是
prompt("Please enter a number to sum the square").split(",").map(Number)
您也不能同時聲明並開始使用total
; 您會得到NaN。 在循環之前聲明並初始化它:
var total = 0;
for (var index = 0; index < sumsqs.length; index++) {
total += sumsqs[index] * sumsqs[index];
}
var inputNumber = Number(prompt("Please enter a number to sum the square"));
document.write("<h1>The sum of squares is " +
((inputNumber * (inputNumber + 1) * (2 * inputNumber + 1))/6) + ".</h1>");
它使用此處提到的公式來計算結果。 http://library.thinkquest.org/20991/gather/formula/data/209.html
感謝大家的反饋。 我只是覺得有點晚了。 這是我完成作業的工作。 我能夠在Web控制台的幫助下解決問題。
再次感謝!
var sumsqs = [];
var sumsq = Number(prompt("Please enter a number to calculate the sum the square or -1 to stop"));
while (sumsq != -1) {
sumsqs.push(sumsq);
sumsq = Number(prompt("Please enter a number to calculate the sum the square or -1 to stop"));
}
var total_sumsqs = 0;
for (var index = 0; index < sumsqs.length; index++) {
total_sumsqs = total_sumsqs + sumsqs[index] * sumsqs[index];
}
document.write("<h3>The sum of squares is " + total_sumsqs + ".</h3>");
您可以使用以下表達式計算逗號分隔列表的平方和:
Math.hypot(...prompt().split`,`)**2
說明:
...prompt().split`,`
接受用戶輸入,並創建使用從輸入的陣列,
作為分隔符。 然后,使用散布運算符將結果數組的元素轉換為Math.hypot()
參數。
Math.hypot()
返回其參數平方和的平方根,因此,如果使用冪運算符將結果提高為2
的冪 ,則可以獲得平方和。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.