求前100个斐波那契数

  这个是在微博上看到的一个题目,题目并不难,只要按照斐波那契数的求法写出过程就可以了。唯一需要注意的是,不能直接使用整型(即使是long long)来进行计算,不然会出现整型溢出的情况。所以,我用了两个数组来保存数并模拟加法过程来实现。

我的代码如下:
 
 1 #include <iostream>
 2 #include <string.h>
 3 #define weishu 30
 4 using namespace std;
 5 int first[weishu];
 6 int last[weishu];
 7 int main()
 8 {
 9     int jishu=2;
10     cout<<0<<endl<<1<<endl;
11     bool flag=false;
12     memset(first,0,sizeof(first));
13     memset(last,0,sizeof(last));
14     last[0]=1;
15     while(jishu<=100){
16         int jinwei=0;
17         for(int i=0;i<weishu;i++){
18             if(flag==false){
19                 int temp=first[i]+last[i]+jinwei;
20                 first[i]=temp%10;
21                 jinwei=temp/10;
22             }
23             else{
24                 int temp=first[i]+last[i]+jinwei;
25                 last[i]=temp%10;
26                 jinwei=temp/10;
27             }
28         }
29         
30         if(flag==false){
31             int j;
32             for(j=weishu-1;j>=0;j--){
33                 if(first[j]==0) continue;
34                 else{
35                     break;
36                 }
37             }
38             for(;j>=0;j--) {
39                 cout<<first[j];
40             } 
41             cout<<endl;
42             flag=true;
43         }
44         else {
45             int j;
46             for(j=weishu-1;j>=0;j--){
47                 if(last[j]==0) continue;
48                 else{
49                     break;
50                 }
51             }
52             for(;j>=0;j--) {
53                 cout<<last[j];
54             }
55             cout<<endl;
56             flag=false;    
57         }
58         jishu++;
59     }
60     return 0;
61 }

 

posted @ 2015-08-17 10:50  Num.Zero  阅读(2903)  评论(0编辑  收藏  举报