2016-02-12 58 views
-1

正如标题所示,我有一个斐波那契数列的代码,我的目标是用系列数字替换数字中的多个数字(3,5,7和它们的组合)字。我被建议在我的if循环中使用一个标志来检查打印的短语,如果打印了该短语,则跳过该数字。从本质上讲,我想要的输出样子是:使用标记方法替换Fibonacci系列中的多个数字

1 1 2 8跳过跳过13 34 55

(这是只更换三个多,现在)。

相反,我所得到的是:

1 1 2 3 skip5 8月13日21 skip34 55

这里是我的代码截至目前:

int febCount = 50; 
long[] feb = new long[febCount]; 
feb[0] = 1; 
feb[1] = 1; 
for (int i = 2; i < febCount; i++) { 
feb[i] = feb[i - 1] + feb[i - 2]; 
} 

for (int i = 0; i < febCount; i++) { 
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " ")); 
if (feb[i] % 3 == 0) 
    System.out.print("skip"); 
} 

任何及所有帮助不胜感激!

+0

你试过调试你的代码吗? –

+0

我看到没有语法错误:/ – ExiLe

+0

如果出现语法错误,您的代码将永远不会编译。调试将导致您发现问题。我会给你一个提示:事情是按正确的顺序执行的吗? –

回答

0

让我们来看看您提供的代码,并试图理解它为什么不起作用。

//The first thing we do is setup the loop to iterate through the fib numbers. 
//This looks good. 
for (int i = 0; i < febCount; i++) { 
//Here we print out the fibonacci number we are on, unconditionally. 
//This means that every fibonacci number will be printed no matter what number it is 
//we don't want that. 
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " ")); 
//After we print the number, we check to see if it is a multiple of three. 
//maybe we should be waiting to print until then? 
if (feb[i] % 3 == 0) 
    System.out.print("skip"); 
} 

既然我们已经走过了代码,我们可以提出一个新的解决方案。 让我们尝试更新循环,以便它等待打印斐波那契数字,直到我们检查完它后是否符合条件。

for (int i = 0; i < febCount; i++) { 
    if (feb[i] % 3 == 0 || feb[i] % 5 == 0 || feb[i] % 7 == 0) { //check if multiple of 3 5 or 7 
     System.out.println(" Skip "); 
    } else { //if it's not a multiple, then print the number 
     System.out.println(" " + feb[i]); 
    } 
} 
+0

这很有道理。非常感谢。我一整天都在想这件事情,而且这是关于打印它的订单的问题。 – ExiLe

+0

如果我想用另一个短语替换5的倍数和7的倍数,会出现什么情况? – ExiLe

+0

现在我们把代码的写法写成同样的东西,你的第一步应该是让每一个都是他们自己的情况 – dustinroepsch

相关问题