任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
这个实际上编译为没有任何条件的程序集:
#include <stdio.h>
#include <stdlib.h>
void main(int j) {
printf("%d\n", j);
(&main + (&exit - &main)*(j/1000))(j+1);
}
编辑:添加了'&',因此它将考虑地址,从而避免指针错误。
上面的这个版本在标准C中,因为它不依赖于函数指针的算术:
#include <stdio.h>
#include <stdlib.h>
void f(int j)
{
static void (*const ft[2])(int) = { f, exit };
printf("%d\n", j);
ft[j/1000](j + 1);
}
int main(int argc, char *argv[])
{
f(1);
}
其他回答
#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);
}
和这里的其他人相比有点无聊,但可能是他们想要的。
#include <stdio.h>
int f(int val) {
--val && f(val);
return printf( "%d\n", val+1);
}
void main(void) {
f(1000);
}
简单C版本,在1000处终止:
int print_stuff(int count) {
printf("%d\n", count);
return (count ^ 1000) && print_stuff(count+1);
}
int main(int argc, char *argv[]) {
print_stuff(1);
return 0;
}
适合c++爱好者
int main() {
std::stringstream iss;
iss << std::bitset<32>(0x12345678);
std::copy(std::istream_iterator< std::bitset<4> >(iss),
std::istream_iterator< std::bitset<4> >(),
std::ostream_iterator< std::bitset<4> >(std::cout, "\n"));
}
经过一些修改,我想出了这个:
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;
}