任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
递归?
#include<stdio.h>
#define MAX 1000
int i = 0;
void foo(void) {
if(i <= 1000) {
printf("%d", i);
i++;
}
}
int main (void) {
foo();
}
其他回答
我假设,由于这个问题的性质,扩展是不排除的?
而且,我很惊讶,到目前为止还没有人去。
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;
}
好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)
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; }
编译时递归!: 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语言,使用整数除法从数组中选择函数指针。此外,它在没有警告的情况下正确编译和执行,甚至在没有警告的情况下传递“夹板”。
当然,我也受到了很多其他答案的启发。即便如此,我的更好。
#include <stdio.h>
#include <stdlib.h>
static int x(/*@unused@*/ const char * format, ...) { exit(0); }
static void p(int v, int e) {
static int (*a[])(const char *, ...) = { printf, x };
(void)a[v/(e+1)]("%d\n", v);
p(v+1, e);
}
int main(void) {
p(1, 1000);
return 0;
}
使用宏压缩:
#include <stdio.h>
#define a printf("%d ",++i);
#define b a a a a a
#define c b b b b b
#define d c c c c c
#define e d d d d
int main ( void ) {
int i = 0;
e e
return 0;
}
或者更好:
#include <stdio.h>
#define a printf("%d ",++i);
#define r(x) x x x x x
#define b r(r(r(a a a a)))
int main ( void ) {
int i = 0;
b b
return 0;
}