js实现计算平均数的代码

js实现计算平均数的代码,js实现计算平均数的方法教程如下:

输入一组数据

实现结果:计算出这组数据的平均数

js实现代码如下:

    function isNum(arg)
    {
      var args = arg;
      var fad = true;
      if (args == "" || args == null || args.length == 0) {
        return false;
      }
      args = args.toString();
      for (var i = 0; i < args.length; i++) {
        if (args.substring(i, i + 1) < "0" || args.substring(i, i + 1) > "9") {
          if (args.substring(i, i + 1) == ".") {
            if (fad == true)
              fad = false;
            else
              return false;
          }
          else {
            return false;
          }
        }
      }
      return true;
    }

    function quickSort(arr) {
    var arr = arr.concat(); //concat鐨勬柊鐢ㄦ硶(娣卞鍒�)
    if(arr.length<=1) return arr;
    var index = Math.floor(arr.length/2);
    var centerValue = arr.splice(index,1);
    //console.log(centerValue);
    var left = [];
    var right = [];
    for(var i=0,len=arr.length;i<len;i++){
        if(centerValue>=arr[i]){
            left.push(arr[i]);
        }else{
            right.push(arr[i]);
        }
    }
    // debugger
    //console.log(quickSort(left));
    //console.log(right);
    var res1 = arguments.callee(left);
    var res2 = arguments.callee(right);
    //return left.concat(right);
    return res1.concat(centerValue,res2);
  }

    function calculate() {
      var x = document.getElementById("inputs").value;
      x = x.replace(' ', '');
      var arr = x.split(',');
      for (var v = 0; v < arr.length; v++) {
        var d = arr[v];
        if (isNaN(d) || d == "") {
          alert("杩欎釜鏁板瓧 \"" + d + "\" 涓嶆槸鏈夋晥鐨勬暟瀛�");
          var bb = false;
          break;
        }
      }

      var lcm = 0;
      var flag = false;
      var arithmeticTotal = 0; // arithmetic mean
      var geometricTotal = 1;

      for (var j = 0; j < arr.length; j++) {
        arr[j] = parseFloat(arr[j]);
        arithmeticTotal += arr[j];
        geometricTotal *= arr[j];
      }
      var arithmeticMean = Math.round(arithmeticTotal / arr.length * 10000) / 10000;

      var geometricMean = Math.pow(geometricTotal, 1 / arr.length);
      geometricMean = Math.round(geometricMean * 10000) / 10000;

      var soreArr = quickSort(arr);
      console.log(arr)
      var median = soreArr.length % 2 === 1 ? soreArr[(soreArr.length+1)/2 -1] : (soreArr[soreArr.length/2 -1] + soreArr[soreArr.length/2]) / 2;

      document.getElementById("res_area").style.visibility = "visible";

      document.getElementById("result1").value = arr.length;
      document.getElementById("result2").value = arithmeticMean;
      document.getElementById("result3").value = geometricMean;
      document.getElementById("result5").value = median;
    }
显示效果:平均数计算器

参考文章:http://tishang.net/articles/1685780330.html

快乐下载

软件屋下载

中元手游网

铁盒下载

unix时间戳

分数计算器

平均数计算器

URL编码

Unicode编码转换

robots文件在线生成

posted @ 2023-06-03 16:24  kaiser099  阅读(74)  评论(0编辑  收藏  举报