计算 java 中的斐波那契数
calculating fibonacci numbers in java
我正在尝试使用 java 中的模型视图控制器方法显示前 20 个斐波那契数。但是,我得到的输出只是最后一个数字(前 19 个未显示),如果有人能够查看我的代码并指出我哪里出错了,那就太棒了:)
public class斐波那契模型{
public String fibModel(int a, int b, int c, int count){
String result = "";
//int c;
while(count!=20) // if you want first 100 fibonacci numbers then change 20 to 100 accordingly
{
c=a+b;
count++;
result = c + " ";
a=b;
b=c;
}
return result;
}
}
public class 斐波那契控制器 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 1;
int b = 1;
int count = 2;
int c = 0;
FibonacciModel Model = new FibonacciModel();
FibonacciView View = new FibonacciView();
View.say(Model.fibModel(a, b, c, count));
}
}
public class FibonacciView {
public < T > void say( T word ){
System.out.print(word);
}
}
您正在覆盖结果变量。尝试 result = result + c + " ";
或 result += c + " ";
看看这个:)
public static void getFibbonacci(int n){
int total = 0;
int prev = 1;
for (int x=1; x<n; x++){
total = total + prev;
prev = total - prev;
System.out.println(total);
}
}
public class fibbo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a;
System.out.println("Enter the number");
a = sc.nextInt();
int first = 0;
int second = 1;
int third;
System.out.print("Fibbonacci series is= ");
System.out.print("\t" + first + "\t" + second + "\t");
for (int i = 0; i < a - 2; i++) {
third = first + second;
first = second;
second = third;
System.out.print(third + "\t");
}
}
我正在尝试使用 java 中的模型视图控制器方法显示前 20 个斐波那契数。但是,我得到的输出只是最后一个数字(前 19 个未显示),如果有人能够查看我的代码并指出我哪里出错了,那就太棒了:)
public class斐波那契模型{
public String fibModel(int a, int b, int c, int count){
String result = "";
//int c;
while(count!=20) // if you want first 100 fibonacci numbers then change 20 to 100 accordingly
{
c=a+b;
count++;
result = c + " ";
a=b;
b=c;
}
return result;
}
}
public class 斐波那契控制器 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 1;
int b = 1;
int count = 2;
int c = 0;
FibonacciModel Model = new FibonacciModel();
FibonacciView View = new FibonacciView();
View.say(Model.fibModel(a, b, c, count));
}
}
public class FibonacciView {
public < T > void say( T word ){
System.out.print(word);
}
}
您正在覆盖结果变量。尝试 result = result + c + " ";
或 result += c + " ";
看看这个:)
public static void getFibbonacci(int n){
int total = 0;
int prev = 1;
for (int x=1; x<n; x++){
total = total + prev;
prev = total - prev;
System.out.println(total);
}
}
public class fibbo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a;
System.out.println("Enter the number");
a = sc.nextInt();
int first = 0;
int second = 1;
int third;
System.out.print("Fibbonacci series is= ");
System.out.print("\t" + first + "\t" + second + "\t");
for (int i = 0; i < a - 2; i++) {
third = first + second;
first = second;
second = third;
System.out.print(third + "\t");
}
}