博客
关于我
斐波那契数列(辅助数组)
阅读量:376 次
发布时间:2019-03-05

本文共 954 字,大约阅读时间需要 3 分钟。

    
#include 
#include
#define Size 3void Fib(int n){ long *S = (long *)malloc(Size * sizeof(long)); S[0] = 1; S[1] = 1; if (n == 1) { printf("%ld\n", S[0]); } else if (n == 2) { printf("%ld %ld\n", S[0], S[1]); } else { int i = 3; S[2] = 2; printf("%d %d ", 1, 1); while (i <= n) { printf("%ld ", S[2]); S[0] = S[1]; S[1] = S[2]; S[2] = S[1] + S[0]; i++; } printf("\n"); } return;}int main(){ int n; scanf("%d", &n); if (n >= 1) { Fib(n); } else { printf("error!\n"); } return 0;}

这段代码实现了斐波那契数列的计算功能。首先,程序包含了必要的头文件<stdio.h><stdlib.h>。定义了一个常量Size为3,用于内存分配。函数Fib用于计算斐波那契数列,接受一个整数参数n表示要计算的项数。程序通过动态内存分配为数列元素预留空间,并初始化前两项为1。对于n等于1和2的情况,分别输出单独的数值或两个数值。对于更大的n,程序使用循环从第三项开始计算,并每次循环更新当前项的值。最后,程序在main函数中读取输入的项数n,并根据其值调用Fib函数或输出错误信息。

转载地址:http://husg.baihongyu.com/

你可能感兴趣的文章
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>