在Java中的数组查找的平均 [英] Finding the average in an array in Java

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

问题描述

我必须找到在一个数组是从一个特定的号码(例如不同的元件的平均值:{2,6,4,7,7,4,2,5}是阵列如何找到平均从4个不同的元素?)


解决方案

 进口java.util.Scanner中;公共类ArrAvg {公共静态无效的主要(字串[] args){    诠释一个[] = {1,2,3,4,5,6,7,8,9,10};
    INT发生= 0;
    双总和= 0;
    双平均= 0;    的for(int i = 0; I<则为a.length;我++){        如果(一个由[i] == 4){
            发生++;
        }
    }
    的for(int i = 0; I<则为a.length;我++){        如果(一个由[i]!= 4){
            总和=总和+ A [];
        }
    }
    的System.out.println(平均=总和/(则为a.length-发生));    }}

I have to find the average value of the elements in an array that are different from a specific number (example: {2,6,4,7,7,4,2,5} is the array. How to find the average of the elements different from 4?)

解决方案

import java.util.Scanner;

public class ArrAvg {

public static void main(String[] args) {

    int a[] = {1,2,3,4,5,6,7,8,9,10};
    int occur = 0;
    double sum = 0;
    double avg = 0;

    for (int i = 0; i < a.length; i++) {

        if (a[i] == 4) {
            occur++;
        }
    }
    for (int i = 0; i < a.length; i++) {

        if (a[i] != 4) {
            sum =  sum + a[i];
        }
    }
    System.out.println(avg = sum / (a.length-occur));

    }

}

这篇关于在Java中的数组查找的平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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