[英]Is it possible to calculate Fibonacci sequence by preprocessor directives in C?
Just for personal study and better understanding of C code preprocessor:仅供个人学习和更好地理解C代码预处理器:
I am wondering if it is possible to implement Fibonacci function by preprocessor directives in C language.我想知道是否可以通过 C 语言的预处理器指令来实现斐波那契function。
Normal definition of Fibonacci function could be:斐波那契 function 的正常定义可能是:
int f(int i) { // i should be non-negative integer
if (i <= 1) {
return 1;
}
return f(i - 1) + f(i - 2);
}
The approach of using the template metaprogramming technique in C++ is not what I need.在 C++ 中使用模板元编程技术的方法不是我需要的。
It seems that it is not possible to perform recursive calculations by using the code preprocessor?使用代码预处理器似乎无法进行递归计算?
I do not think macro in C can support recursive macro.我不认为 C 中的宏可以支持递归宏。 But Fibonacci is possible macro.
但斐波那契是可能的宏。 By using the fomular of nth number
通过使用第 n 个数的公式
#define Fibonacci(n) (POW(1+POW(5,1/2),n) - POW(1-POW(5,1/2),n))/POW(5,1/2)
Recursive macros are not allowed in C or in C++. C 或 C++ 中不允许使用递归宏。
Macros — just a text replacement, not computation宏——只是一个文本替换,而不是计算
Using boost preprocessor's slots, and an iterative solution, with the macro I
as input:使用 boost 预处理器的插槽和迭代解决方案,以宏
I
作为输入:
#ifndef INITIALIZE
#define INITIALIZE
# include <boost/preprocessor/slot.hpp>
# if I<=2
1
# else
# define BOOST_PP_VALUE 2
# include BOOST_PP_ASSIGN_SLOT(1)
# define BOOST_PP_VALUE 1
# include BOOST_PP_ASSIGN_SLOT(3)
# define BOOST_PP_VALUE 1
# include BOOST_PP_ASSIGN_SLOT(4)
# include __FILE__
# endif
#else
# define BOOST_PP_VALUE BOOST_PP_SLOT(1) + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# define BOOST_PP_VALUE BOOST_PP_SLOT(3)
# include BOOST_PP_ASSIGN_SLOT(2)
# define BOOST_PP_VALUE BOOST_PP_SLOT(4)
# include BOOST_PP_ASSIGN_SLOT(3)
# define BOOST_PP_VALUE BOOST_PP_SLOT(2) + BOOST_PP_SLOT(3)
# include BOOST_PP_ASSIGN_SLOT(4)
# if I==BOOST_PP_SLOT(1)
BOOST_PP_SLOT(4)
# else
# include __FILE__
# endif
#endif
Demo: http://coliru.stacked-crooked.com/a/c399d11dedc306ca演示: http://coliru.stacked-crooked.com/a/c399d11dedc306ca
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.