【问题标题】:An array that will declare 5 random numbers from 0 to 100. Then it will average all the numbers that are over 70一个数组,它将声明 5 个从 0 到 100 的随机数。然后它将平均所有超过 70 的数字
【发布时间】:2016-10-01 02:48:30
【问题描述】:

这是我需要回答的作业问题。

编写一个完整的程序,声明一个包含从 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 的数字从其他人不是。

【问题讨论】:

    标签: java arrays eclipse average


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 哇,这行得通。不过,我确实必须在计数器 ++ 之后立即删除 System.out.print。这使得该程序看起来有超过 5 个数字。所以,我需要做一个总计和计数器变量,以便我可以将计数器与总计相除。我正在查看这个,我想我现在明白了。谢谢!
    【解决方案2】:

    您可以简单地跟踪有多少数字超过 70 以及它们的总和是多少。 公共静态无效主要(字符串[]参数){ 随机数 = 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(平均); }

    【讨论】:

    • 谢谢你。感谢您花时间回答。
    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多