我正在编写一个包含方法numdiv的程序,该方法可以找到d的除数。我还有一个名为sumSquares的方法,该方法可以找到1和n之间的平方。我在主要方法中放置了一个for循环,以找到10到50的平方和除数,直到现在才想找到b / w 10和50的平均除数。这是代码:


    public static void main(String[] args) {
        System.out.println("NUMBER\tSUM OF SQUARES\tDIVISORS");//setup table
        //loop through numbers 10 to 50
        for(int i = 10; i <= 50; i++){ //i represents the integers to print
            System.out.println(i + "\t" + sumSquares(i) + "\t\t" + numdiv(i));
        }
    }

    public static int sumSquares(int n){
        int sum = 0; //define sum
        for(int num = 1; num <= n; num++){
            sum = (num*num) + sum; //set sum equal to num*num then add to sum
        }
        return sum;
    }

    public static int numdiv(int d){
        int div = 0; //counter for divisors

        for(int num = 1; num <= d; num++){
            if(d % num == 0){ //check if d is a divisor
                div++; //increment div each time true
            }
        }
        return div;
    }
}


有人知道我该怎么做吗?

最佳答案

根据您的方法,无需更改它们即可保持逻辑,您可以将main方法更改如下:

public static void main(String[] args) {
    System.out.println("NUMBER\tSUM OF SQUARES\tDIVISORS");//setup table
    //loop through numbers 10 to 50
    int sumSquares = 0;
    int numDiv = 0;
    int totalSquares = 0;
    int totalDiv = 0;
    for(int i = 10; i <= 50; i++){ //i represents the integers to print
        sumSquares = sumSquares(i);
        numDiv = numdiv(i);
        System.out.println(i + "\t" + sumSquares + "\t\t" + numDiv);
        totalSquares += sumSquares;
        totalDiv += numDiv;
    }
    System.out.printf("Average sumSquares: %d - Average numDiv: %d", totalSquares/41, totalDiv/41);
}


注意:我已经对41除数进行了硬编码,因为您也对10和50之间的数字进行了硬编码。您应该对此进行外部化,并且还要for循环编号。

关于java - 如何计算Java中除数的平均数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58422084/

10-16 07:36