任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
我假设,由于这个问题的性质,扩展是不排除的?
而且,我很惊讶,到目前为止还没有人去。
int main () {
int i = 0;
void * addr[1001] = { [0 ... 999] = &&again};
addr[1000] = &&end;
again:
printf("%d\n", i + 1);
goto *addr[++i];
end:
return 0;
}
好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)
其他回答
我假设,由于这个问题的性质,扩展是不排除的?
而且,我很惊讶,到目前为止还没有人去。
int main () {
int i = 0;
void * addr[1001] = { [0 ... 999] = &&again};
addr[1000] = &&end;
again:
printf("%d\n", i + 1);
goto *addr[++i];
end:
return 0;
}
好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)
不懂足够的C(++)来写代码,但你可以使用递归而不是循环。为了避免这种情况,可以使用在第1000次访问后抛出异常的数据结构。例如,某种带有范围检查的列表,在每次递归时增加/减少索引。
从评论中判断,c++中似乎没有任何范围检查列表?
相反,你可以用1/n作为递归函数的参数,每次调用都减少1。从1000开始。DivisionByZero异常将停止递归
编译时递归!: 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);
}
令人惊讶的是,如果你放弃了“必须是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
Manglesky的解决方案很棒,但还不够模糊。: -):
#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d\n", i++);))) return 0; }