任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
不懂足够的C(++)来写代码,但你可以使用递归而不是循环。为了避免这种情况,可以使用在第1000次访问后抛出异常的数据结构。例如,某种带有范围检查的列表,在每次递归时增加/减少索引。
从评论中判断,c++中似乎没有任何范围检查列表?
相反,你可以用1/n作为递归函数的参数,每次调用都减少1。从1000开始。DivisionByZero异常将停止递归
其他回答
令人惊讶的是,如果你放弃了“必须是C或c++”的要求,事情会变得多么简单:
Unix shell:
echo {1..1000} | tr ' ' '\n'
or
yes | nl | awk '{print $1}' | head -1000
如果你在一个没有yes命令的Unix变体上运行,使用其他进程至少生成1000行:
find / 2> /dev/null | nl | awk '{print $1}' | head -1000
or
cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000
or
head -1000 /etc/termcap | nl -s: | cut -d: -f1
既然对bug没有限制…
int i=1; int main() { int j=i/(i-1001); printf("%d\n", i++); main(); }
或者更好(?),
#include <stdlib.h>
#include <signal.h>
int i=1;
int foo() { int j=i/(i-1001); printf("%d\n", i++); foo(); }
int main()
{
signal(SIGFPE, exit);
foo();
}
以下是我知道的三个解决方案。不过,第二种说法可能存在争议。
// compile time recursion
template<int N> void f1()
{
f1<N-1>();
cout << N << '\n';
}
template<> void f1<1>()
{
cout << 1 << '\n';
}
// short circuiting (not a conditional statement)
void f2(int N)
{
N && (f2(N-1), cout << N << '\n');
}
// constructors!
struct A {
A() {
static int N = 1;
cout << N++ << '\n';
}
};
int main()
{
f1<1000>();
f2(1000);
delete[] new A[1000]; // (3)
A data[1000]; // (4) added by Martin York
}
[编辑:(1)和(4)只能用于编译时常数,(2)和(3)也可以用于运行时表达式-结束编辑。]]
受到Orion_G的回答和reddit讨论的启发;使用函数指针和二进制算术:
#include <stdio.h>
#define b10 1023
#define b3 7
typedef void (*fp) (int,int);
int i = 0;
void print(int a, int b) { printf("%d\n",++i); }
void kick(int a, int b) { return; }
void rec(int,int);
fp r1[] = {print, rec} ,r2[] = {kick, rec};
void rec(int a, int b) {
(r1[(b>>1)&1])(b10,b>>1);
(r2[(a>>1)&1])(a>>1,b);
}
int main() {
rec(b10,b3);
return 1;
}
#include <stdio.h>
int show(int i) {
printf("%d\n",i);
return( (i>=1000) || show(i+1));
}
int main(int argc,char **argv) {
return show(1);
}
||操作符使递归调用短路,以显示i为>= 1000时的情况。