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

用C或c++怎么做呢?


当前回答

看起来它不需要使用循环

printf("1 10 11 100 101 110 111 1000\n");

其他回答

如果你打算使用编译时递归,那么你可能还想使用分治法来避免触及模板深度限制:

#include <iostream>

template<int L, int U>
struct range
{
    enum {H = (L + U) / 2};
    static inline void f ()
    {
        range<L, H>::f ();
        range<H+1, U>::f ();
    }
};

template<int L>
struct range<L, L>
{
    static inline void f ()
    {
        std::cout << L << '\n';
    }
};

int main (int argc, char* argv[])
{
    range<1, 1000>::f ();
    return 0;
}

函数指针(ab)使用。没有预处理器的魔力来增加输出。ANSI C。

#include <stdio.h>

int i=1;

void x10( void (*f)() ){
    f(); f(); f(); f(); f();
    f(); f(); f(); f(); f();
}

void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }

int main(){
    M();
}

简单C版本,在1000处终止:

int print_stuff(int count) {
   printf("%d\n", count);
   return (count ^ 1000) && print_stuff(count+1);
 }

 int main(int argc, char *argv[]) {
   print_stuff(1);
   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; }

递归?

#include<stdio.h>
#define MAX 1000

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