簡體   English   中英

一個數組,它將聲明5個從0到100的隨機數。然后它將對超過70的所有數字求平均值

[英]An array that will declare 5 random numbers from 0 to 100. Then it will average all the numbers that are over 70

這是我需要回答的作業問題。

編寫一個完整的程序,聲明一個從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的數字相互隔離的嘗試。不是。

嘗試這個:

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

}

您可以簡單地跟蹤70以上有多少個數字,以及它們的總和。 public static void main(String [] args){Random 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(平均值); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM