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

用C或c++怎么做呢?


当前回答

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

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

其他回答

#include <iostream>
#include <vector>

using namespace std;
#define N 10    //10 or 1000, doesn't matter

class A{
public:
    A(){
        //cout << "A(): " << m_ << endl;    //uncomment to show the difference between gcc and Microsoft C++ compiler
    }
    A(const A&){
        ++m_;
        cout << m_ << endl;     
    }
private:
    static int m_;  //global counter
};

int A::m_(0);  //initialization

int main(int argc, char* argv[])
{
    //Creates a vector with N elements. Printing is from the copy constructor, 
    //which is called exactly N times.
    vector<A> v(N);  
    return 0;   
}

实现注意: 使用gcc:默认构造函数创建一个“master”元素。 然后元素被复制构造函数复制N次。 在微软c++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。

编译时递归!: P

#include <iostream>
template<int N>
struct NumberGeneration{
  static void out(std::ostream& os)
  {
    NumberGeneration<N-1>::out(os);
    os << N << std::endl;
  }
};
template<>
struct NumberGeneration<1>{
  static void out(std::ostream& os)
  {
    os << 1 << std::endl;
  }
};
int main(){
   NumberGeneration<1000>::out(std::cout);
}

被接受答案的c++变体:

void print(vector<int> &v, int ind)
{
    v.at(ind);
    std::cout << ++ind << std::endl;
    try
    {
        print(v, ind);
    }
    catch(std::out_of_range &e)
    {
    }
}

int main()
{
    vector<int> v(1000);
    print(v, 0);
}

令人惊讶的是,如果你放弃了“必须是C或c++”的要求,事情会变得多么简单:

Unix shell:

echo {1..1000} | tr ' ' '\n'

or

yes | nl | awk '{print $1}' | head -1000

如果你在一个没有yes命令的Unix变体上运行,使用其他进程至少生成1000行:

find / 2> /dev/null | nl | awk '{print $1}' | head -1000

or

cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000

or

head -1000 /etc/termcap | nl -s: | cut -d: -f1
#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;
}