任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
你可以非常简单地使用递归和强制错误…
另外,请原谅我的c++代码非常草率。
void print_number(uint number)
{
try
{
print_number(number-1);
}
catch(int e) {}
printf("%d", number+1);
}
void main()
{
print_number(1001);
}
其他回答
我对这个美妙的答案集的一点贡献(它返回零):
#include <stdio.h>
int main(int a)
{
return a ^ 1001 && printf("%d\n", main(a+1)) , a-1;
}
逗号运算符为FTW \o/
你可以非常简单地使用递归和强制错误…
另外,请原谅我的c++代码非常草率。
void print_number(uint number)
{
try
{
print_number(number-1);
}
catch(int e) {}
printf("%d", number+1);
}
void main()
{
print_number(1001);
}
#include<iostream>
#include<stdexcept>
using namespace std;
int main(int arg)
{
try
{
printf("%d\n",arg);
int j=1/(arg-1000);
main(arg+1);
}
catch(...)
{
exit(1);
}
}
#include <stdio.h>
#include <stdlib.h>
void print(int n)
{
int q;
printf("%d\n", n);
q = 1000 / (1000 - n);
print(n + 1);
}
int main(int argc, char *argv[])
{
print(1);
return EXIT_SUCCESS;
}
它最终会停止:P
也可以通过简单的动态调度来实现(在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);
}