如何解决斐波那契数列将不打印任何内容,但由用户输入的数字
这是我的主要方法,我试图调用斐波那契数列来告诉我用户输入的位置将是什么数字:
file = open("encoder2.pkl","rb")
encoder = pickle.load(file)
file.close()
data2 = {'flag': ['SF','SF','S0','REJ']}
df2 = pd.DataFrame(data=data2,columns=['flag'])
X = encoder.transform(df2['flag'])
print(X)
这是我的斐波那契代码:
import java.util.Scanner; //import Scanner
public class Main {
public static void main(String[] args) {
System.out.println("enter number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
Fibonacci fibonacci_test = new Fibonacci();
fibonacci_test.Recursivefibonacci(n);
}
}
我不能用这个东西打印任何东西。我该如何解决?
解决方法
这是因为您没有打印其他任何东西。 您的方法不打印任何内容(只返回一个值),而您的主体不打印任何内容(“输入数字”除外)。
您可以尝试将Publish
更改为Merge
返回Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
比将其存储在变量中更合适。
我是在python中完成的,您可以看一下,尝试将其适应Java,这可能会对您有所帮助。递归可能会让人头疼,但看起来不错。
def fib(n):
if n == 0:
return 0
if n <= 1:
return 1
res = (fib(n-1)+ fib(n-2))
return res
//////// 可能您的代码看起来像这样:
public int Recursivefibonacci(int n) {
if(n == 0){
return 0;
}
if(n <= 1) {
return 1;
}
int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
return fib;
}
尝试一下!让我知道它是否有效。
,尝试使用此代码获取递归斐波那契序列:
import java.math.BigInteger;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number : ");
BigInteger n = sc.nextBigInteger();
if (n.signum() == -1) {
System.out.println("Negative number entered. Failed.");
sc.close();
return;
}
System.out.println("The fibonacci series of " + n + " terms is : " + fibonacciSequence(n));
sc.close();
}
public static BigInteger fibonacciSequence(BigInteger n) {
if (n.equals(BigInteger.ONE) || n.equals(BigInteger.ZERO)) {
return n;
}
return fibonacciSequence(n.subtract(new BigInteger("2"))).add(fibonacciSequence(n.subtract(BigInteger.ONE)));
}
}
这适用于大多数情况(包括大量情况):
Enter the number :
0
The fibonacci series of 0 terms is : 0
Enter the number :
1
The fibonacci series of 1 terms is : 1
Enter the number :
-1
Negative number entered. Failed.
Enter the number :
10
The fibonacci series of 10 terms is : 55
Enter the number :
14
The fibonacci series of 14 terms is : 377
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。