我有一个关于在Java中生成Fibonacci数的初学者问题。
在这个java程序中,该方法应该打印从BeginIndex
到LastIndex
的Fibonnacci数字序列,因此如果数字是5的倍数,它应该打印"Hi"
(而不是数字) ,如果数字是7的倍数,请打印"I am"
,如果数字是35的倍数,请打印"Hi I am me"
。我不确定如何执行此操作。
class FibonacciClass {
public static void main(String args[] ) throws Exception {
generatefibonacci(10, 20);
generatefibonacci(0, 1);
}
private static void generatefibonacci(int BeginIndex, int LastIndex) {
}
答案 0 :(得分:1)
另一种可能性:
private static void generateFibonacci(int beginIndex, int lastIndex) {
int len = lastIndex + 1;
int[] fib = new int[len];
fib[0] = 0;
fib[1] = 1;
// Building Fibonacci sequence from beginIndex through lastIndex
for (int i = 2; i < len; ++i)
fib[i] = fib[i-1] + fib[i-2];
// Printing
for (int index = beginIndex; index <= lastIndex; ++index) {
if ((fib[index] % 5 == 0) && (fib[index] % 7 == 0)) {
System.out.println("Hi I am me");
}
else if (fib[index] % 5 == 0) {
System.out.println("Hi");
}
else if (fib[index] % 7 == 0) {
System.out.println("I am");
}
else {
System.out.println(fib[index]);
}
}
}
答案 1 :(得分:0)
您正在寻找的是模数运算符%。它将通过其操作数返回除法的余数。因此,从if(x%5 == 0&amp;&amp; x%7 == 0)接收真值将表示数字x是5和7的倍数。如果这种情况没有通过,你应该使用else if语句单独检查x是5的倍数然后是另一个if if是7的倍数,每个if分支调用System.out.println(&#34; x是y&#34的倍数;) ;
答案 2 :(得分:0)
每次 generatefibonacci 都会产生一个你必须用模数(%)检查的结果。
像这样:
hcf
所以这只是一个小例子。 玩得开心
答案 3 :(得分:0)
private static void generatefibonacci(int BeginIndex, int LastIndex) {
int[] numbers = new int[LastIndex + 2]; //creates an array to put fibonacci numbers in
numbers[0] = 1; numbers[1] = 1;
for(int i = 2; i <= LastIndex; i ++){
numbers[i] = numbers[i - 1] + numbers[i - 2]; //generates the Fibonacci Sequence
}
for(int i = BeginIndex; i <= LastIndex; i ++){
if(numbers[i] % 5 == 0 && numbers[i] % 7 == 0){//if the remainder when the numbers/5 equals 0 and the remainder when the numbers/7 equals 0
System.out.println("Hello I am me");
}
else if(numbers[i] % 5 == 0){ //if the remainder when the numbers/5 equals 0
System.out.println("I am");
}
else if(numbers[i] % 7 == 0){ //if the remainder when the numbers/7 equals 0
System.out.println("Hi");
}
else{ //if none of the above three conditions are true
System.out.println(numbers[i]);
}
}
}