用Java写一个斐波那契数列
时间: 2023-05-13 09:05:58 浏览: 87
好的,以下是用Java写斐波那契数列的代码:
public class Fibonacci {
public static void main(String[] args) {
int n = 10, t1 = 0, t2 = 1;
System.out.print("前 " + n + " 个斐波那契数列: ");
for (int i = 1; i <= n; ++i) {
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
这段代码可以输出前10个斐波那契数列的值。
相关问题
用java写一个斐波那契数列
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
int a = 0;
int b = 1;
int fib = 0;
for (int i = 2; i <= n; i++) {
fib = a + b;
a = b;
b = fib;
}
return fib;
}
}
//输出结果:0 1 1 2 3 5 8 13 21 34
用JAVA写一个斐波那契数列
public class FibonacciSequence {
public static void main(String[] args) {
int n = 10;
for(int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if(n == 0) {
return 0;
}
if(n == 1 || n == 2) {
return 1;
}
int a = 1, b = 1, c = 0;
for(int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
阅读全文