如何打印斐波那契数列,每第四个数字跳过一次,用 X 替换跳过并从 0 开始
How to print the Fibonacci sequence, skipping every fourth number, replaces the skips with X and starts from 0
/*我能够输出:0, 1, 1, X2, 3, 5, 8, X13, 21, 34, 55, X89, 144, 233, 377, X610, 987, 1597, 2584、X4181、6765,但是,我似乎可以让它跳过数字并用 Q 替换它们。我坚持这个。 :(
import java.util.ArrayList;
import java.util.List;
public class FibonacciSequence {
public static void main(String[] args) {
long f = 0;
List<Integer> testList = new ArrayList<Integer>();
boolean executed;
for(int i = 1; i<=21; i++) {
f = fib(i);
String space = ", ";
if(i%4==0) {
String x = "X";
System.out.print(x);
}
System.out.print(fib(i) + ", ");
}
}
private static long fib(int i) {
if (i == 1) {
return 0;
}
if (i <= 2) {
return 1;
}
else {
return fib(i-1)+fib(i-2);
}
}
}
假设我理解你的问题,请在 if
之外使用 else
。我清理了您的 main
方法,删除了您未使用的变量。在检查我们不在第一个元素上之后,我会简单地在前面添加 ,
。喜欢,
public static void main(String[] args) {
for (int i = 1; i <= 21; i++) {
if (i != 1) {
System.out.print(", ");
}
if (i % 4 == 0) {
System.out.print("X");
} else {
System.out.print(fib(i));
}
}
}
/*我能够输出:0, 1, 1, X2, 3, 5, 8, X13, 21, 34, 55, X89, 144, 233, 377, X610, 987, 1597, 2584、X4181、6765,但是,我似乎可以让它跳过数字并用 Q 替换它们。我坚持这个。 :(
import java.util.ArrayList;
import java.util.List;
public class FibonacciSequence {
public static void main(String[] args) {
long f = 0;
List<Integer> testList = new ArrayList<Integer>();
boolean executed;
for(int i = 1; i<=21; i++) {
f = fib(i);
String space = ", ";
if(i%4==0) {
String x = "X";
System.out.print(x);
}
System.out.print(fib(i) + ", ");
}
}
private static long fib(int i) {
if (i == 1) {
return 0;
}
if (i <= 2) {
return 1;
}
else {
return fib(i-1)+fib(i-2);
}
}
}
假设我理解你的问题,请在 if
之外使用 else
。我清理了您的 main
方法,删除了您未使用的变量。在检查我们不在第一个元素上之后,我会简单地在前面添加 ,
。喜欢,
public static void main(String[] args) {
for (int i = 1; i <= 21; i++) {
if (i != 1) {
System.out.print(", ");
}
if (i % 4 == 0) {
System.out.print("X");
} else {
System.out.print(fib(i));
}
}
}