求前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 }

 

转载于:https://www.cnblogs.com/xiongmao-cpp/p/4736015.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值