简体   繁体   English

Java 如何计算数组中数字的平均值?

[英]Java How can I calculate the average of numbers in an array?

I'm stuck with my program.我被我的程序困住了。 What it does, is basically it generates 100 random numbers into an array.它所做的基本上是将 100 个随机数生成到一个数组中。 It prints the numbers in 4 lines.它以 4 行打印数字。 After that, another for loop checks if there are numbers, which can be divided by seven, and are even at the same time.之后,另一个 for 循环检查是否有数字,这些数字可以被 7 整除,并且同时是偶数。 If there are, it inserts them into another array.如果有,它会将它们插入到另一个数组中。 Now, we don't know how many numbers like that are in the random array, so that's where I stuck basically.现在,我们不知道随机数组中有多少这样的数字,所以这就是我基本上坚持的地方。 I have the sum of the numbers in the array.我有数组中数字的总和。 But can't calculate the pieces of elements.但无法计算元素的碎片。

import static java.lang.System.out;
import java.util.Random;


public class CSharp {

    public static void main(String[] args) {
        Random r = new Random();
        int[] numbers = new int[100];
        int[] canBeDividedBySeven = new int[100];
        int c = 0;
        int sum = 0;
        int average = 0;

        out.println("Random numbers: ");
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] += r.nextInt(90) + 10;

            out.print(numbers[i] + " ");
            if (i % 35 == 0) {  
                out.print("\n");
            }
        }

        out.println("\n\nNumbers that can be divided by 7 and are even: ");
        for (int j = 0; j < numbers.length; j++) {
            if (numbers[j] % 7 == 0 && numbers[j] % 2 == 0) {
                out.print(numbers[j] + " ");
                canBeDividedBySeven[c] += numbers[j];
            }
        }
        out.println("\n\nThe sum of the numbers in the 'canBeDividedBySeven': ");
        for (int y = 0; y < canBeDividedBySeven.length; y++) {
            sum += canBeDividedBySeven[y++];

        }
        out.print(sum);

    }

}

You are missing 1 part - incrementing c when adding it to the array canBeDividedBySeven .c添加到数组canBeDividedBySeven时,您缺少 1 部分 - 递增c If you do this, you can get the average just by doing (double) sum / c .如果你这样做,你可以通过做(double) sum / c来获得平均值。

Basically your canBeDividedBySeven array looks like [3283, 0, 0, 0, ..99 0's] if you increment c ( canBeDividedBySeven[c ++ ] += numbers[j]; ) it will look like [14, 28, 14, 42, ...0, 0, 0] , which you can find the "size" of this array with the variable c.基本上你的canBeDividedBySeven数组看起来像[3283, 0, 0, 0, ..99 0's]如果你增加 c ( canBeDividedBySeven[c ++ ] += numbers[j]; ) 它看起来像[14, 28, 14, 42, ...0, 0, 0] ,您可以使用变量 c 找到该数组的“大小”。 The actual size will always just be 100.实际大小总是只有 100。

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM