任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。

用C或c++怎么做呢?


当前回答

既然对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();
}

其他回答

令人惊讶的是,如果你放弃了“必须是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; }

易如反掌!: P

#include <iostream>

static int current = 1;

struct print
{
    print() { std::cout << current++ << std::endl; }
};

int main()
{
    print numbers [1000];
}
#include <stdio.h>
int main(int argc, char** argv)
{
printf("numbers from 1 to 1000\n");
}

递归?

#include<stdio.h>
#define MAX 1000

int i = 0;
void foo(void) {
    if(i <= 1000) {
         printf("%d", i);
         i++;
    }
}
int main (void) {
    foo();
}