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

用C或c++怎么做呢?


当前回答

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

其他回答

除了基本的字符串处理,你真的不需要任何东西:

#include <iostream>
#include <algorithm>

std::string r(std::string s, char a, char b)
{
    std::replace(s.begin(), s.end(), a, b);
    return s;
}

int main()
{
    std::string s0 = " abc\n";
    std::string s1 = r(s0,'c','0')+r(s0,'c','1')+r(s0,'c','2')+r(s0,'c','3')+r(s0,'c','4')+r(s0,'c','5')+r(s0,'c','6')+r(s0,'c','7')+r(s0,'c','8')+r(s0,'c','9');
    std::string s2 = r(s1,'b','0')+r(s1,'b','1')+r(s1,'b','2')+r(s1,'b','3')+r(s1,'b','4')+r(s1,'b','5')+r(s1,'b','6')+r(s1,'b','7')+r(s1,'b','8')+r(s1,'b','9');
    std::string s3 = r(s2,'a','0')+r(s2,'a','1')+r(s2,'a','2')+r(s2,'a','3')+r(s2,'a','4')+r(s2,'a','5')+r(s2,'a','6')+r(s2,'a','7')+r(s2,'a','8')+r(s2,'a','9');
    std::cout << r(r(s1,'a',' '),'b',' ').substr(s0.size())
          << r(s2,'a',' ').substr(s0.size()*10)
          << s3.substr(s0.size()*100)
          << "1000\n";
}

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

// 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)也可以用于运行时表达式-结束编辑。]]

未经测试,但应该是香草标准C:

void yesprint(int i);
void noprint(int i);

typedef void(*fnPtr)(int);
fnPtr dispatch[] = { noprint, yesprint };

void yesprint(int i) {
    printf("%d\n", i);
    dispatch[i < 1000](i + 1);
}

void noprint(int i) { /* do nothing. */ }

int main() {
    yesprint(1);
}

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<iostream>
#include<stdexcept>

using namespace std;

int main(int arg)

{
    try

    {

        printf("%d\n",arg);
        int j=1/(arg-1000);
        main(arg+1);
    }

    catch(...)
    {
        exit(1);
    }
}