我编写了一个程序来显示java中的斐波纳契系列,但现在我希望序列中的数字以十位显示,即一行上的前十个斐波纳契数字,接着是下一行的下十个,所以... ... 我一直遇到真正的问题。
这是该计划:
import java.util.Scanner;
import java.math.BigInteger;
class Fibonacci {
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
int number = new Scanner(System.in).nextInt();
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
for (int i = 1; i <= number; i++) {
System.out.println(fibonacciLoop(i) + " ");
}
}
public static BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}
答案 0 :(得分:8)
print
(不要println
)将每个号码放在同一行。只要您的计数器i
是10的倍数,就开始换行。
for (int i = 1; i <= number; i++) {
System.out.print(fibonacciLoop(i) + " ");
if (i % 10 == 0)
System.out.println();
}
答案 1 :(得分:2)
if(i % 10 == 0)
{
System.out.println();
}
或者如果你想成为幻想。
System.out.print(fibonacciLoop(i) + " " + (i % 10 == 0? "\n":""));
答案 2 :(得分:0)
请注意,由于以下for循环,您的斐波纳契计算不起作用:
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
以下内容将按照您的要求执行:
import java.math.BigInteger;
import java.util.Scanner;
import java.util.LinkedList;
public class Test {
Test(int number) {
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
LinkedList<BigInteger> list = new LinkedList<BigInteger>();
for (int i = 1; i <= number; i++) {
list.add(fibonacciLoop(i));
if(list.size() == 10) {
printFibo(list);
list = new LinkedList<BigInteger>();
}
}
if(!list.isEmpty()) printFibo(list);
}
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
new Test(new Scanner(System.in).nextInt());
}
private void printFibo(LinkedList<BigInteger> list) {
for(BigInteger fiboNumber : list) {
System.out.print(fiboNumber + " ");
}
System.out.println("");
}
public BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}