提取号码
问题描述:
如何使用宏而不是函数提取包含在另一个号码中的号码。提取号码
示例伪代码:
#define extract_number(int number, // original number
int pos, // start position from behind (1 == first digit)
int len) // count of digits
{
...
}
main() {
int number = 0;
int result = 0;
number = 123456789;
result = extract_number(number, 2, 3); // result: 678
number = 987123456;
result = extract_number(number, 4, 4); // result: 7123
}
编辑2016年9月21日: 我要做的ATM如下:
int number = 123456789;
int result = number/10 % 1000;
使用张贴@Frzn FLMS功能的版本是这样的我会已经在一个函数中完成了它。有没有办法在编译时使用宏来完成它?
答
例如:2应该由10被替换和3应由1000
代替它使用升压如下被写入。
#include <stdio.h>
#include <boost/preprocessor/control/while.hpp>
#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/cat.hpp>
#define PRED(d, state) BOOST_PP_TUPLE_ELEM(2, 0, state)
#define OP(d, state) (BOOST_PP_DEC(BOOST_PP_TUPLE_ELEM(2, 0, state)), BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, state), 0))
#define pow0(n) BOOST_PP_TUPLE_ELEM(2, 1, BOOST_PP_WHILE(PRED, OP, (BOOST_PP_ADD(n,1), 1)))
int main(void) {
int n = pow0(2);//1000: "1" + "0"✕(n+1)
printf("%d\n", n);
return 0;
}
我投票结束这个问题作为题外话,因为它显然是写我的代码请求,而不是问题。请先阅读[问]页面。 :) –
到目前为止请显示您的研究/调试工作。请先阅读[问]页面。 –
你的意思是找到那个数字的主要因素? – Olaf