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

用C或c++怎么做呢?


当前回答

触发致命错误!这是文件,counup .c:

#include <stdio.h>
#define MAX 1000
int boom;
int foo(n) {
    boom = 1 / (MAX-n+1);
    printf("%d\n", n);
    foo(n+1);
}
int main() {
    foo(1);
}

编译,然后在shell提示符下执行:

$ ./countup
1
2
3
...
996
997
998
999
1000
Floating point exception
$

这确实打印了从1到1000的数字,没有任何循环或条件!

其他回答

c++利用RAII

#include <iostream>
using namespace std;

static int i = 1;
struct a
{
    a(){cout<<i++<<endl;}
    ~a(){cout<<i++<<endl;}
}obj[500];

int main(){return 0;}

C语言开发宏

#include <stdio.h>

#define c1000(x) c5(c5(c5(c4(c2(x))))) 
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x))   //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x

int main(int i){c1000(printf("%d\n",i++);)return 0;}

编辑:还有一个,这个很简单

#include <stdio.h>
#define p10(x) x x x x x x x x x x
int main(int i){p10(p10(p10(printf("%d\n",i++);)))return 0;} 

解析:选C

编辑:此c代码包含<=和?:操作符

#include <stdio.h>

int main(int i){return (i<=1000)?main(printf("%d\n",i++)*0 + i):0;}
template <int remaining>
void print(int v) {
 printf("%d\n", v);
 print<remaining-1>(v+1);
}

template <>
void print<0>(int v) {
}

print<1000>(1);

我假设,由于这个问题的性质,扩展是不排除的?

而且,我很惊讶,到目前为止还没有人去。

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(void) {
    printf(" 1 2 3 4 5 6 7 8");
    return 0;
}

我打赌1000是二进制的 他显然是在检查这家伙的CQ (compSci商数)

我对这个美妙的答案集的一点贡献(它返回零):

#include <stdio.h>

int main(int a)
{
    return a ^ 1001 && printf("%d\n", main(a+1)) , a-1;
}

逗号运算符为FTW \o/