任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include<stdio.h>
int b=1;
int printS(){
printf("%d\n",b);
b++;
(1001-b) && printS();
}
int main(){printS();}
其他回答
我对这个美妙的答案集的一点贡献(它返回零):
#include <stdio.h>
int main(int a)
{
return a ^ 1001 && printf("%d\n", main(a+1)) , a-1;
}
逗号运算符为FTW \o/
正如它是回答:)
在不使用任何循环或条件语句的情况下,从1到1000的数字。不要只写printf()或cout语句1000次。”);
#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);
}
有趣的函数指针(不需要新流行的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);
经过一些修改,我想出了这个:
template<int n>
class Printer
{
public:
Printer()
{
std::cout << (n + 1) << std::endl;
mNextPrinter.reset(new NextPrinter);
}
private:
typedef Printer<n + 1> NextPrinter;
std::auto_ptr<NextPrinter> mNextPrinter;
};
template<>
class Printer<1000>
{
};
int main()
{
Printer<0> p;
return 0;
}
后来@ybungalobill的作品启发我想出了这个更简单的版本:
struct NumberPrinter
{
NumberPrinter()
{
static int fNumber = 1;
std::cout << fNumber++ << std::endl;
}
};
int main()
{
NumberPrinter n[1000];
return 0;
}