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

用C或c++怎么做呢?


当前回答

该任务从未指定程序必须在1000之后终止。

void f(int n){
   printf("%d\n",n);
   f(n+1);
}

int main(){
   f(1);
}

(如果你run ./a,可以缩写为this。没有额外的参数)

void main(int n) {
   printf("%d\n", n);
   main(n+1);
}

其他回答

#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++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。

触发致命错误!这是文件,counup .c:

#include <stdio.h>
#define MAX 1000
int boom;
int foo(n) {
    boom = 1 / (MAX-n+1);
    printf("%d\n", n);
    foo(n+1);
}
int main() {
    foo(1);
}

编译,然后在shell提示符下执行:

$ ./countup
1
2
3
...
996
997
998
999
1000
Floating point exception
$

这确实打印了从1到1000的数字,没有任何循环或条件!

使用指针算术,我们可以将数组自动初始化为0。

#include <stdio.h>

void func();
typedef void (*fpa)();
fpa fparray[1002] = { 0 };

int x = 1;
void func() {
 printf("%i\n", x++);
 ((long)fparray[x] + &func)();
}

void end() { return; }

int main() {
 fparray[1001] = (fpa)(&end - &func);
 func();
 return 0;
}
#include <stdio.h>

typedef void (*fp) (int);

void stop(int i)
{
   printf("\n");
}

void next(int i);

fp options[2] = { next, stop };

void next(int i)
{
   printf("%d ", i);
   options[i/1000](++i);
}

int main(void)
{
   next(1);
   return 0;
}
template <int To, int From = 1>
struct printer {
    static void print() {
        cout << From << endl; 
        printer<To, From + 1>::print();
    }
};    

template <int Done>
struct printer<Done, Done> {
     static void print() {
          cout << Done << endl;
     }
};

int main() 
{
     printer<1000>::print();
}