任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
system("/usr/bin/env echo {1..1000}");
其他回答
也可以通过简单的动态调度来实现(在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);
}
简单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;
}
下面是使用信号的POSIX变体:
#include <stdio.h>
#include <signal.h>
void counter(int done)
{
static int i;
done = ++i / 1000;
printf("%d\n", i);
signal(SIGINT, (void (*)(int))(done * (int)SIG_DFL + (1-done) * (int)&counter));
raise(SIGINT);
}
int main()
{
signal(SIGINT, &counter);
raise(SIGINT);
return 0;
}
有趣的部分是counter()对signal()的调用。在这里,将安装一个新的信号处理程序:如果"done"为真,则SIG_DFL,否则计数器。
为了使这个解决方案更加可笑,我使用了信号处理程序所需的int形参来保存临时计算的结果。作为一个副作用,恼人的“未使用变量”警告在使用gcc -W -Wall编译时消失。
我不打算写代码,只写想法。让一个线程每秒打印一个数字,然后另一个线程在1000秒后杀死第一个线程怎么样?
注:第一个线程通过递归生成数字。
函数指针(ab)使用。没有预处理器的魔力来增加输出。ANSI C。
#include <stdio.h>
int i=1;
void x10( void (*f)() ){
f(); f(); f(); f(); f();
f(); f(); f(); f(); f();
}
void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }
int main(){
M();
}