zoukankan      html  css  js  c++  java
  • 求前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 }
    ——来自 熊猫 [http://www.cnblogs.com/xiongmao-cpp/]
  • 相关阅读:
    window10 禁止更新
    安装node.msi 格式的文件失败
    url参数的转码和解码
    Linux12-内存管理
    C++四种cast
    Linux内核5-系统调用
    Linux内核3-进程管理
    UNIX12-线程(下)线程控制
    UNIX11-线程(上)
    Linux内核8-中断下半部和推后执行的工作(下半部)
  • 原文地址:https://www.cnblogs.com/xiongmao-cpp/p/4736015.html
Copyright © 2011-2022 走看看