标题:费波那契数列问题
只看楼主
greenpop
Rank: 1
等 级:新手上路
帖 子:73
专家分:3
注 册:2011-12-22
结帖率:88.24%
已结贴  问题点数:20 回复次数:2 
费波那契数列问题
#include<stdio.h>
int main()
{
    int a=1,b=1;
    int m,n;
    int i;
    printf("请输入项数:\n");
    scanf("%d",&m);
    if(m%2==0)
    {
        n=m/2;
         for(i=0;i<n;i++)
        {
        printf("%d %d ",a,b);
        a=a+b;
        b=a+b;
        }
    }
    else
    {
        n=m/2;
       for(i=0;i<n;i++)
            {
             printf("%d %d ",a,b);
             a=a+b;
             b=a+b;
            }
            printf("%d",a);
        }
    return 0;

}
各位大佬,为什么上面的程序运行到47项以后,会出现负数。谢谢指教。
搜索更多相关主题的帖子: 数列 int printf for i++ 
2019-06-09 19:56
吕孟伟
Rank: 8Rank: 8
等 级:贵宾
威 望:27
帖 子:200
专家分:870
注 册:2018-10-4
得分:20 
数列计算到后面数字太大,int类型存放不了,出现负数。
程序代码:
#include<stdio.h>
int main()
{
    double a=1,b=1;
    int m,n;
    int i;
    printf("请输入项数:\n");
    scanf("%d",&m);
    if(m%2==0)
    {
        n=m/2;
         for(i=0;i<n;i++)
        {
        printf("%25.0lf %25.0lf \n",a,b);
        a=a+b;
        b=a+b;
        }
    }
    else
    {
        n=m/2;
       for(i=0;i<n;i++)
            {
             printf("%25.0lf %25.0lf \n",a,b);
             a=a+b;
             b=a+b;
            }
            printf("%25.0lf",a);
        }
    return 0;

}
}

代码输出:
请输入项数:
47
                        1                         1
                        2                         3
                        5                         8
                       13                        21
                       34                        55
                       89                       144
                      233                       377
                      610                       987
                     1597                      2584
                     4181                      6765
                    10946                     17711
                    28657                     46368
                    75025                    121393
                   196418                    317811
                   514229                    832040
                  1346269                   2178309
                  3524578                   5702887
                  9227465                  14930352
                 24157817                  39088169
                 63245986                 102334155
                165580141                 267914296
                433494437                 701408733
               1134903170                1836311903
               2971215073

[此贴子已经被作者于2019-6-9 20:37编辑过]


借用一下侯捷的话:勿在浮沙筑高台。
2019-06-09 20:16
蒟蒻
Rank: 1
等 级:新手上路
帖 子:20
专家分:0
注 册:2019-11-11
得分:0 
回复 2楼 吕孟伟
要是再大点的数超过double的范围又该怎么办
2019-12-10 16:23



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-495174-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.081406 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved