2016-10-17 84 views
0

我想设计一个程序,输出给定一定数量的术语运行的每个斐波那契数的模数。我也希望这个程序输出的数字是偶数,可以被5整除,或者是全零。所以基本上它需要每循环运行三分之一,五分之一和十五分之一时的特定输出,因此我试图使用一堆if语句。如果你可以请指导我在正确的方向或告诉我什么样的代码/格式使用,我想我会弄清楚。谢谢。如何获得for循环的特定运行时间的特定输出?

sample output: for a 17 term input 
    1: 1 
    2: 1 
    3: 2 - even 
    4: 3 
    5: 5 - divisible by 5 
    6: 8 - even 
    7: 3 
    8: 1 
    9: 4 - even 
    10: 5 - divisible by 5 
    11: 9 
    12: 4 - even 
    13: 3 
    14: 7 
    15: 0 - even -divisible by 5 - ends in zero 
    16: 7 
    17: 7 


#include <iostream> 
using namespace std; 

int main() 
{ 

    int terms, n, next1, next2, first = 0, second = 1; 




    cout << "Welcome to the Fibonacci sequence checker!" << endl; 
    cout << "How many terms do you want to check?" << endl; 
    cin >> terms; 


    for (int n = 1; n < terms; n++) 
     { 
    if (n <= 1) 
     next2 = n; 

    else 
     { 
     next1 = first + second; 
     next2 = (first + second) % 10; 
     first = second; 
     second = next1; 
     } 

    if(next2 == 2 || next2 == 4 || next2 == 6 || next2 == 8) 
     { 
     cout << next2 << " - even"; 
     } 
    if(next2 == 5) 
     { 
     cout << next2 << " - divisible by 5"; 
      } 
    if(next2 == 0) 
     { 
     cout << " - even - divisible by 5 - ends in a zero"; 
     } 


     } 


    return 0; 
} 

输出样本: 1:1 2:1 3:2 - 甚至 4:3 5:5 - 整除5 6:8 - 甚至 7:3 8:1 9:4 - 甚至 10:5 - 整除5 11:9 12:4 - 甚至 13:3 14:7 15:0 - 即使由5 -divisible - 终止于零 16:7 17:7

回答

0

首先,要检查数字是否只是检查模数2,不需要检查最后一位数字是2还是4或6或8.我会用next1%2==0,next1%5==0next1%10==0,您还需要更改每cout<<next2cout<<next1,因为next2next1的10的模数。另外作为一个很好的做法,我建议你阅读Straustrup C++书来获取C++的基础知识。

+0

我对描述进行了修改并添加了一个示例输出。 – PrivatePatron