用java输入一个数据n,计算斐波那契数列的第n个值。斐波那契数列为 1,1,2,3,4,8,13,21,34,......
时间: 2024-09-23 10:01:19 浏览: 63
在Java中,你可以使用递归或循环的方式来计算斐波那契数列的第n个值。这里给出一种常见的迭代方法,因为它更高效,避免了递归带来的性能开销:
```java
import java.util.Scanner;
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 0) {
throw new IllegalArgumentException("Input should be a positive integer.");
} else if (n == 1 || n == 2) {
return n - 1; // 因为题目描述是从1开始计数的,所以1和2对应的是0和1
}
int prev = 0;
int current = 1;
for (int i = 3; i <= n; i++) {
int next = prev + current;
prev = current;
current = next;
}
return current;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个正整数:");
int n = scanner.nextInt();
int result = fibonacci(n);
System.out.printf("斐波那契数列的第%d个值是: %d%n", n, result);
}
}
```
阅读全文