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

用C或c++怎么做呢?


当前回答

立足c++概念,传承gcc、vc

[root@localhost ~]# cat 1.cpp
#include <stdio.h>
#include <stdlib.h>

int i = 1;
void print(int arg0)
{
    printf("%d ",i);
    *(&arg0 - 1) = (int)print;
    *(&arg0 - i/1000) = (int)exit;
    i++;
}
int main(void) {
    int a[1000];
    print(0);
    return 0;
}

运行:

[root@localhost ~]# g++ 1.cpp -o 1
[root@localhost ~]# ./1

1 2 ... 1000

其他回答

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

        typedef void(*word)(int);

        word words[1024];

        void print(int i) {
                printf("%d\n", i);
                words[i+1](i+1);
        }

        void bye(int i) {
                exit(0);
        }

        int main(int argc, char *argv[]) {
                words[0] = print;
                words[1] = print;
                memcpy(&words[2], &words[0], sizeof(word) * 2); // 0-3
                memcpy(&words[4], &words[0], sizeof(word) * 4); // 0-7
                memcpy(&words[8], &words[0], sizeof(word) * 8); // 0-15
                memcpy(&words[16], &words[0], sizeof(word) * 16); // 0-31
                memcpy(&words[32], &words[0], sizeof(word) * 32); // 0-63
                memcpy(&words[64], &words[0], sizeof(word) * 64); // 0-127
                memcpy(&words[128], &words[0], sizeof(word) * 128); // 0-255
                memcpy(&words[256], &words[0], sizeof(word) * 256); // 0-511
                memcpy(&words[512], &words[0], sizeof(word) * 512); // 0-1023
                words[1001] = bye;
                words[1](1);
        }

易如反掌!: P

#include <iostream>

static int current = 1;

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

int main()
{
    print numbers [1000];
}

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

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 "stdafx.h"
static n=1;
class number {
public:
    number () {
        std::cout << n++ << std::endl;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    number X[1000];
    return 0;
}

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

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

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;
}

好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)