1

我在计算 javascript 中的平方和时遇到问题。当我定义 for 循环和变量索引时,我迷路了。谁能帮我理解我做错了什么?

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

谢谢你,维

4

4 回答 4

5

例如,如果您希望将逗号分隔的数字列表转换为数字数组,那不是

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];
}
于 2013-09-29T18:48:48.153 回答
0

感谢大家的反馈。我只是看到它有点太晚了。这是我为完成任务所做的。我能够在网络控制台的帮助下弄清楚。

再次感谢!

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>");
于 2013-10-05T23:49:01.090 回答
0
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

于 2013-09-29T18:58:13.247 回答
0

您可以使用以下表达式计算逗号分隔列表的平方和:

Math.hypot(...prompt().split`,`)**2

解释:

...prompt().split`,`接受用户输入并使用,作为分隔符从输入创建一个数组。然后将结果数组的元素转换为Math.hypot()使用扩展运算符的参数。

Math.hypot()返回其参数的平方和的平方根,因此如果您将结果提高到2使用幂运算符的幂,您可以获得平方和。

于 2018-10-29T01:39:16.113 回答