我试图编写一个程序的代码,该程序打印的是星号和三角形数字。虽然代码似乎不起作用并且不会打印出任何值,但starNumbers的函数工作正常但我认为三角形数字的函数有点不确定,我不确定问题出在哪里。
非常感谢所有帮助 感谢
public class TriangularNumbers {
public static void main(String[] args) {
int n = 1;
int i = 1;
int star = starNumbers(n);
int triangle = triangleNumbers(i, n);
while (star > 0)
{
while (star < triangle)
{
n++;
star = starNumbers(n);
}
while (triangle < star)
{
triangle = triangleNumbers(i, n);
}
if (star==triangle)
{
System.out.println(star);
}
}
}
private static int starNumbers (int n) {
int s = ((6*n)*(n-1)+1);
return s;
}
private static int triangleNumbers( int i, int n){
int star = starNumbers(n);
int t = 0;
while (t<=star)
{
t = t + i;
i++;
}
return t;
}
}
答案 0 :(得分:0)
这是一个空循环:
while (star > 0);
应该是
while(star > 0)
但是,我发现if(star==traingle)
条件永远不会成立,因此看不到输出。
答案 1 :(得分:-1)
//try this
public class TriangularNumbers {
public static void main(String[] args) {
int n = 1;
int i = 1;
int star = starNumbers(n);
int triangle = 0;
while (star > 0){
star = starNumbers(n++);
triangle=0;
//System.out.println("Star "+star);
while(triangle < star){
triangle = triangleNumbers(i,star);
if(star == triangle){
System.out.println("match at "+star);
}
}
}
}
private static int starNumbers (int n) {
int s = ((6*n)*(n-1)+1);
return s;
}
private static int triangleNumbers( int i, int star){
int t = 0;
while (t<star){
t = i*(i+1)/2; //get next triangle
i++;
}
return t;
}
}