一个数组,它将声明从0到100的5个随机数。然后它将平均所有超过70的数字

时间:2016-10-01 02:48:31

标签: java arrays eclipse average

这是我需要回答的功课问题。

编写一个完整的程序,声明一个从0到100的任意五个整数的数组,并且只对那些大于70的整数求平均值。

这是我到目前为止编写的代码。

import java.util.Random;
public class TestLoop{ 

    public static void main(String[] args){
        Random Rnum = new Random();
        int[] ar1 = new int[100];
        for(int i = 0; i < 5; i++) {
            ar1[i] = Rnum.nextInt(100);
               System.out.print(ar1[i] + "  ");

        if(ar1[i] > 70)    

            System.out.print(ar1[i] + "  ");
        }
    }
}

这允许我得到我的五个随机数,但我似乎无法弄清楚如何平均那些将超过70的数字。最后几行代码是我试图孤立的数字其他70多个不是。

2 个答案:

答案 0 :(得分:0)

试试这个:

public static void main(String[] args){
    Random Rnum = new Random();
    int[] ar1 = new int[100];
    int counter=0;
    double total=0;
    for(int i = 0; i < 5; i++) {
        ar1[i] = Rnum.nextInt(100);
           System.out.print(ar1[i] + "  ");

        if(ar1[i] > 70)
        {    
            total+=ar1[i];
            counter++;
            System.out.print(ar1[i] + "  ");
        }
    }
    if(counter>0)
    {
        double average=total/counter;
        System.out.println("average="+average);
    }

}

答案 1 :(得分:0)

您可以简单地跟踪70以上的数字以及它们的总和。 public static void main(String [] args){     随机Rnum = new Random();

//added variables
int count = 0;
int average = 0;

int[] ar1 = new int[100];
for(int i = 0; i < 5; i++) {
    ar1[i] = Rnum.nextInt(100);
       System.out.print(ar1[i] + "  ");

if(ar1[i] > 70)    
    // increment count
    count++;
    // add the number greater than 70 to the average
    average += ar[i];
    System.out.print(ar1[i] + "  ");
}

//once out of the loop devide the sum of all     //integers greater than 70 (stored in average) by //the number of integers that were greater than 70 (stored in count)

平均=平均/计数;

的System.out.println(平均); }