importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[] args){Scanner input =newScanner(System.in);int k = input.nextInt();int f1 =1;// f(k-1)int f2 =1;// f(k-2)int fk =1;// f(k)/* 整数i标记当前项的编号,i从3开始,到k为止,步长为1 */for(int i =3; i <= k; i++){
fk = f1 + f2;// 计算当前项f(k)
f2 = f1;// 更新f(k-2)
f1 = fk;// 更新f(k-1)}System.out.print(fk);}}
五、C++程序
#include<iostream>usingnamespace std;intmain(){int k;
cin >> k;int f1 =1;// f(k-1)int f2 =1;// f(k-2)int fk =1;// f(k)/* 整数i标记当前项的编号,i从3开始,到k为止,步长为1 */for(int i =3; i <= k; i++){
fk = f1 + f2;// 计算当前项f(k)
f2 = f1;// 更新f(k-2)
f1 = fk;// 更新f(k-1)}
cout << fk;return0;}