[英]How do I calculate the average number of divisors in Java
I'm making a program that contains the method numdiv
which finds the number of divisors of d
.我正在制作一个包含方法numdiv
的程序,该方法找到d
的除数。 I also have a method called sumSquares
which finds the squares between 1 and n
.我还有一个叫做sumSquares
的方法,它可以找到 1 和n
之间的平方。 I've put a for loop in the main method to find sum of squares and divisors of 10 through 50, only now I want to find the average number of divisors b/w 10 and 50. Here's the code:我在 main 方法中放置了一个 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;
}
}
Anyone have an idea of how I can do that please?有人知道我该怎么做吗?
Based on your methods, without changing them to keep your logic, you can change your main
method to be like this:根据您的方法,无需更改它们以保持您的逻辑,您可以将您的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);
}
Note : I've hardcoded the 41 divisor because you have the numbers between 10 and 50 harcoded as well.注意:我已经对 41 除数进行了硬编码,因为您也对 10 到 50 之间的数字进行了硬编码。 You should externalize this and also you for
loop numbers.你应该把它和你for
循环数外部化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.