阵列总数和平均数 [英] Array Sum and Average

查看:107
本文介绍了阵列总数和平均数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有加一个数组中的所有元素,以及平均出来的问题。我将如何做到这一点,用code我现在有实现它?元件被假设为我有它下面将要定义。

 <脚本类型=文/ JavaScript的>
//<![CDATA [VAR我;
VAR elmt =新的Array();elmt [0] =0;
elmt [1] =1;
elmt [2] =2;
elmt [3] =3;
elmt [4] =4;
elmt [5] =7;
elmt [6] =8;
elmt [7] =9;
elmt [8] =10;
elmt [9] =11;//此处问题
为(ⅰ= 9;我小于10;我+ +)
{
    的document.write(所有元素的总和为:+ / *问题这里* / +的所有元素的平均值为:+ / *问题这里* / +&所述峰; br />中);
}//]]>
< / SCRIPT>


解决方案

  VAR总和= 0;
对于(VAR I = 0; I< elmt.length;我++){
    总和+ = parseInt函数(elmt [I],10); //不要忘记添加基地
}VAR平均=总和/ elmt.length;的document.write(所有元素的总和为:+总和+平均是:+平均);

只需通过数组迭代,因为你的价值观是字符串,它们必须首先转换为整数。并且平均是通过值的数目除以值只是总和

I am having problems adding all the elements of an array as well as averaging them out. How would I do this and implement it with the code I currently have? The elements are supposed to be defined as I have it below.

<script type="text/javascript">
//<![CDATA[

var i;
var elmt = new Array();

elmt[0] = "0";
elmt[1] = "1";
elmt[2] = "2";
elmt[3] = "3";
elmt[4] = "4";
elmt[5] = "7";
elmt[6] = "8";
elmt[7] = "9";
elmt[8] = "10";
elmt[9] = "11";

// problem here
for (i = 9; i < 10; i++)
{
    document.write("The sum of all the elements is: " + /* problem here */ + " The average of all the elements is: " + /* problem here */ + "<br/>");
}   

//]]>
</script>

解决方案

var sum = 0;
for( var i = 0; i < elmt.length; i++ ){
    sum += parseInt( elmt[i], 10 ); //don't forget to add the base
}

var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );

Just iterate through the array, since your values are strings, they have to be converted to an integer first. And average is just the sum of values divided by the number of values.

这篇关于阵列总数和平均数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆