任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
堆栈溢出:
#include <stdio.h>
static void print_line(int i)
{
printf("%d\n", i);
print_line(i+1);
}
int main(int argc, char* argv[])
{
//get up near the stack limit
char tmp[ 8388608 - 32 * 1000 - 196 * 32 ];
print_line(1);
}
这是一个8MB的堆栈。每次函数调用大约占用32个字节(因此是32 * 1000)。但是当我运行它时,我只得到804(因此是196 * 32;也许C运行时在堆栈中有其他部分,你也必须扣除)。
其他回答
也可以通过简单的动态调度来实现(在Java中也适用):
#include<iostream>
using namespace std;
class U {
public:
virtual U* a(U* x) = 0;
virtual void p(int i) = 0;
static U* t(U* x) { return x->a(x->a(x->a(x))); }
};
class S : public U {
public:
U* h;
S(U* h) : h(h) {}
virtual U* a(U* x) { return new S(new S(new S(h->a(x)))); }
virtual void p(int i) { cout << i << endl; h->p(i+1); }
};
class Z : public U {
public:
virtual U* a(U* x) { return x; }
virtual void p(int i) {}
};
int main(int argc, char** argv) {
U::t(U::t(U::t(new S(new Z()))))->p(1);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void(*word)(int);
word words[1024];
void print(int i) {
printf("%d\n", i);
words[i+1](i+1);
}
void bye(int i) {
exit(0);
}
int main(int argc, char *argv[]) {
words[0] = print;
words[1] = print;
memcpy(&words[2], &words[0], sizeof(word) * 2); // 0-3
memcpy(&words[4], &words[0], sizeof(word) * 4); // 0-7
memcpy(&words[8], &words[0], sizeof(word) * 8); // 0-15
memcpy(&words[16], &words[0], sizeof(word) * 16); // 0-31
memcpy(&words[32], &words[0], sizeof(word) * 32); // 0-63
memcpy(&words[64], &words[0], sizeof(word) * 64); // 0-127
memcpy(&words[128], &words[0], sizeof(word) * 128); // 0-255
memcpy(&words[256], &words[0], sizeof(word) * 256); // 0-511
memcpy(&words[512], &words[0], sizeof(word) * 512); // 0-1023
words[1001] = bye;
words[1](1);
}
看起来它不需要使用循环
printf("1 10 11 100 101 110 111 1000\n");
template <int To, int From = 1>
struct printer {
static void print() {
cout << From << endl;
printer<To, From + 1>::print();
}
};
template <int Done>
struct printer<Done, Done> {
static void print() {
cout << Done << endl;
}
};
int main()
{
printer<1000>::print();
}
我对这个美妙的答案集的一点贡献(它返回零):
#include <stdio.h>
int main(int a)
{
return a ^ 1001 && printf("%d\n", main(a+1)) , a-1;
}
逗号运算符为FTW \o/