我正在尝试设计一个程序,在给定一定数量的术语的情况下输出每个斐波那契数的模数。我也希望这个程序在数字是偶数时输出,可以被5整除,是零,还是全部三个。所以基本上它需要每三分之一,第五和第十五次循环运行的特定输出,因此我尝试使用一堆if语句。如果你能指导我正确的方向或告诉我使用什么样的代码/格式,我想我能够弄明白。谢谢。
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可分 - 以零结束 16:7 17:7
答案 0 :(得分:0)
首先,检查数字是否只是检查模数是否为2,无需检查最后一位数是2还是4或6或8.我会用next1%2==0
替换所有支票,next1%5==0
和next1%10==0
,您还需要将每cout<<next2
更改为cout<<next1
,因为next2
是next1
的10的模数。另外作为一个好习惯,我建议你阅读Straustrup C ++书籍以获得C ++的基础知识。