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

用C或c++怎么做呢?


当前回答

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

正如它是回答:)

在不使用任何循环或条件语句的情况下,从1到1000的数字。不要只写printf()或cout语句1000次。”);

#include <iostream>

using namespace std;

template<int N>
void func()
{
        func<N-1>();
        cout << N << "\t";
}

template<>
void func<1>()
{
        cout << 1 << "\t";
}

int main()
{
        func<1000>();
        cout << endl;
        return 0;
}

以下是我知道的三个解决方案。不过,第二种说法可能存在争议。

// compile time recursion
template<int N> void f1()
{ 
    f1<N-1>(); 
    cout << N << '\n'; 
}

template<> void f1<1>() 
{ 
    cout << 1 << '\n'; 
}

// short circuiting (not a conditional statement)
void f2(int N)
{ 
    N && (f2(N-1), cout << N << '\n');
}

// constructors!
struct A {
    A() {
        static int N = 1;
        cout << N++ << '\n';
    }
};

int main()
{
    f1<1000>();
    f2(1000);
    delete[] new A[1000]; // (3)
    A data[1000]; // (4) added by Martin York
}

[编辑:(1)和(4)只能用于编译时常数,(2)和(3)也可以用于运行时表达式-结束编辑。]]

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

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