任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
编译时递归!: P
#include <iostream>
template<int N>
struct NumberGeneration{
static void out(std::ostream& os)
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
};
template<>
struct NumberGeneration<1>{
static void out(std::ostream& os)
{
os << 1 << std::endl;
}
};
int main(){
NumberGeneration<1000>::out(std::cout);
}
其他回答
也可以通过简单的动态调度来实现(在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);
}
没人说它不应该事后分段错误,对吧?
注意:这在我的64位Mac OS X系统上正常工作。对于其他系统,您需要将参数更改为setrlimit,并相应地更改spacecew的大小。: -)
(我不应该包括这个,但以防万一:这显然不是一个好的编程实践的例子。然而,它确实有一个优点,那就是它利用了这个网站的名称。)
#include <sys/resource.h>
#include <stdio.h>
void recurse(int n)
{
printf("%d\n", n);
recurse(n + 1);
}
int main()
{
struct rlimit rlp;
char spacechew[4200];
getrlimit(RLIMIT_STACK, &rlp);
rlp.rlim_cur = rlp.rlim_max = 40960;
setrlimit(RLIMIT_STACK, &rlp);
recurse(1);
return 0; /* optimistically */
}
使用指针算术,我们可以将数组自动初始化为0。
#include <stdio.h>
void func();
typedef void (*fpa)();
fpa fparray[1002] = { 0 };
int x = 1;
void func() {
printf("%i\n", x++);
((long)fparray[x] + &func)();
}
void end() { return; }
int main() {
fparray[1001] = (fpa)(&end - &func);
func();
return 0;
}
编译时递归!: P
#include <iostream>
template<int N>
struct NumberGeneration{
static void out(std::ostream& os)
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
};
template<>
struct NumberGeneration<1>{
static void out(std::ostream& os)
{
os << 1 << std::endl;
}
};
int main(){
NumberGeneration<1000>::out(std::cout);
}
该任务从未指定程序必须在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);
}