我正在尝试使用方法找到前100个五角形数字。下面是我的代码,但是,我一直在错过return语句。我确定我没有适当地提交退货声明,除非我不知道这个过程是否正确。因此,我很感激指导。谢谢。 PS:尚未学习阵列,这不是作业
public class PentagonNumber {
public static void main(String[] args) {
int numberperline = 10;
int n = 1;
int count = 0;
int pent = getpentagonnumber(n);
count++;
if (count % numberperline == 0)
System.out.println();
else System.out.print(pent + "\t");
}
public static int getpentagonnumber(int x) {
for (int count = 0; count < 100; count++) {
for (x = 1; x <= 100; x++) {
int result;
result = x * (3 * x - 1) / 2;
return result;
}
}
}
}
答案 0 :(得分:1)
您的代码应该像这样更改:
public class PentagonNumber {
public static void main(String[] args) {
int numberperline = 10;
//int n = 1; // you do not need N
//int count = 0; // you do not this either
for (x = 0; x < 100; x++) { // moved
int pent = getpentagonnumber(x+1); // +1 so it goes 1::100
//count++;
if (x % numberperline == 0)
System.out.println();
//else // you were skipping every tenth result.
System.out.print(pent + "\t");
}// close for
}
public static int getpentagonnumber(int x) {
//for (int count = 0; count < 100; count++) { // moved
//for (x = 1; x <= 100; x++) { // removed
int result; // no need to declare and then calculate
result = x * (3 * x - 1) / 2; // but not wrong either.
return result;
//}
//}
}
}
答案 1 :(得分:-1)
在for循环中只有一个返回值。你可能意味着:
public static int getpentagonnumber(int x ){
int result = 0;
for (int count=0; count<100; count++){
for (x=1;x<=100;x++){
result = x*(3*x-1)/2;
}
} //this was missing
return result;
}