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

用C或c++怎么做呢?


当前回答

看起来它不需要使用循环

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

其他回答

一个脏代码:s

使用xor和数组的函数指针。

#include <stdio.h>
#include <stdlib.h>

typedef void (*fn)(int);
int lst[1001];

void print (int n)
{
  printf ("%d ", n+1);
  go (n+1);
}

void go (int n)
{
  ((fn)(((long)print)^((long)lst[n])))(n);
}

int main ()
{
  lst[1000] = ((long)print)^((long)exit);
  go (0);
}

假设程序以通常的方式(./a.out)运行,因此它有一个参数,并忽略编译器类型警告,那么:

#include <stdio.h>
#include <stdlib.h>

void main(int i) {
    static void (*cont[2])(int) = { main, exit };
    printf("%d\n", i);
    cont[i/1000](i+1);
}

我觉得这个答案会很简单,很容易理解。

int print1000(int num=1)
{
    printf("%d\n", num);

    // it will check first the num is less than 1000. 
    // If yes then call recursive function to print
    return num<1000 && print1000(++num); 
}

int main()
{
    print1000();
    return 0;        
}

经过一些修改,我想出了这个:

template<int n>
class Printer
{
public:
    Printer()
    {        
        std::cout << (n + 1) << std::endl;
        mNextPrinter.reset(new NextPrinter);
    }

private:
    typedef Printer<n + 1> NextPrinter;
    std::auto_ptr<NextPrinter> mNextPrinter;
};

template<>
class Printer<1000>
{
};

int main()
{
    Printer<0> p;
    return 0;
}

后来@ybungalobill的作品启发我想出了这个更简单的版本:

struct NumberPrinter
{
    NumberPrinter()
    {
        static int fNumber = 1;
        std::cout << fNumber++ << std::endl;
    }
};


int main()
{
    NumberPrinter n[1000];
    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();
}