不能返回正确的sum值,矩阵数中的素数

问题描述 投票:-1回答:1

所以我试着从矩阵中得到一个和,所有素数加到变量和。这是我的代码,我无法理解为什么在else语句中它不顺利。

    public static void checkPrimeAVG2DArray() {

    int arr[] [] = {{5, 4, 6}, {11, 15, 9}, {14, 7, 3}};
    double avg = checkPrimeAVG2DArray (arr);
    System.out.println("avg : " + avg); // i revive 176, why?
}
public static double checkPrimeAVG2DArray(int[][] arr) {
    int sum =0;

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



            for (int temp=2; temp < arr[i][j]; temp++ ) {
                if ( arr[i][j] % temp == 0) {
                    temp++;
                    System.out.println(arr[i][j] + " is not prime number");
                    break;

            } else {
                sum = sum + arr[i][j];
            }
    }
    }}
    return sum;
}}
java arrays primes
1个回答
1
投票

您可以通过将主要逻辑提取到单独的方法中然后为2D数组中的每个值调用它来简化操作。

    public static double checkPrimeAVG2DArray(int[][] arr) {
        int sum =0;
        double numberOfPrimesInArray = 0.0;
        for (int i=0; i< arr.length; i++ )
        {
            for (int j=0; j<arr.length; j++)
            {
                if(checkNumberIsPrime(arr[i][j]))
                {
                    numberOfPrimesInArray++;
                    sum += arr[i][j];
                }
            }
        }
        return sum/numberOfPrimesInArray;
    }

  public static boolean checkNumberIsPrime(int valueToCheck)
  {
      int temp;
      for(int i=2;i<=valueToCheck/2;i++)
        {
           temp=valueToCheck%i;
           if(temp==0)
           {
              return false;
           }
        }

      return true;
  }
© www.soinside.com 2019 - 2024. All rights reserved.