![](/img/trans.png)
[英]Is it possible for C preprocessor macros to contain preprocessor directives?
[英]Is it possible to calculate Fibonacci sequence by preprocessor directives in C?
僅供個人學習和更好地理解C代碼預處理器:
我想知道是否可以通過 C 語言的預處理器指令來實現斐波那契function。
斐波那契 function 的正常定義可能是:
int f(int i) { // i should be non-negative integer
if (i <= 1) {
return 1;
}
return f(i - 1) + f(i - 2);
}
在 C++ 中使用模板元編程技術的方法不是我需要的。
使用代碼預處理器似乎無法進行遞歸計算?
我不認為 C 中的宏可以支持遞歸宏。 但斐波那契是可能的宏。 通過使用第 n 個數的公式
#define Fibonacci(n) (POW(1+POW(5,1/2),n) - POW(1-POW(5,1/2),n))/POW(5,1/2)
C 或 C++ 中不允許使用遞歸宏。
宏——只是一個文本替換,而不是計算
使用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.