任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
如果你打算使用编译时递归,那么你可能还想使用分治法来避免触及模板深度限制:
#include <iostream>
template<int L, int U>
struct range
{
enum {H = (L + U) / 2};
static inline void f ()
{
range<L, H>::f ();
range<H+1, U>::f ();
}
};
template<int L>
struct range<L, L>
{
static inline void f ()
{
std::cout << L << '\n';
}
};
int main (int argc, char* argv[])
{
range<1, 1000>::f ();
return 0;
}
其他回答
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>
int main()
{
boost::mpl::for_each<boost::mpl::range_c<unsigned, 1, 1001> >(std::cout << boost::lambda::_1 << '\n');
return(0);
}
该任务从未指定程序必须在1000之后终止。
void f(int n){
printf("%d\n",n);
f(n+1);
}
int main(){
f(1);
}
(如果你run ./a,可以缩写为this。没有额外的参数)
void main(int n) {
printf("%d\n", n);
main(n+1);
}
有趣的函数指针(不需要新流行的TMP):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MSB(typ) ((sizeof(typ) * CHAR_BIT) - 1)
void done(int x, int y);
void display(int x, int y);
void (*funcs[])(int,int) = {
done,
display
};
void done(int x, int y)
{
exit(0);
}
void display(int x, int limit)
{
printf( "%d\n", x);
funcs[(((unsigned int)(x-limit)) >> MSB(int)) & 1](x+1, limit);
}
int main()
{
display(1, 1000);
return 0;
}
附注:我将禁止条件符扩展到逻辑运算符和关系运算符。如果允许逻辑否定,递归调用可以简化为:
funcs[!!(limit-1)](x+1, limit-1);
使用系统命令:
system("/usr/bin/seq 1000");
template <int remaining>
void print(int v) {
printf("%d\n", v);
print<remaining-1>(v+1);
}
template <>
void print<0>(int v) {
}
print<1000>(1);