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

用C或c++怎么做呢?


当前回答

假设程序以通常的方式(./a.out)运行,因此它有一个参数,并忽略编译器类型警告,那么:

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

void main(int i) {
    static void (*cont[2])(int) = { main, exit };
    printf("%d\n", i);
    cont[i/1000](i+1);
}

其他回答

编译时递归!: 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);
}
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>

int main()
{
  boost::mpl::for_each<boost::mpl::range_c<unsigned, 1, 1001> >(std::cout << boost::lambda::_1 << '\n');
  return(0);
}

也许这太明显和容易遵循,但这是标准c++,不转储堆栈和运行在O(n)时间使用O(n)内存。

#include <iostream>
#include <vector>

using namespace std;

int main (int argc, char** args) {
  vector<int> foo = vector<int>(1000);
  int terminator = 0;
 p:
  cout << terminator << endl; 
  try {
    foo.at(terminator++);
  } catch(...) {
    return 0;
  }
  goto p;
}

该任务从未指定程序必须在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);
}

这是我的两个解。第一个是c#,第二个是C语言:

C#:

const int limit = 1000;

Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n);  actions[Math.Sign(limit - n-1)](n + 1); };

actions[1](0);

C:

#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))

void (*actions[3])(int);

void Action0(int n)
{
    printf("%d", n);
}

void Action1(int n)
{
    int index;
    printf("%d\n", n);
    index = sign(998-n)+1;
    actions[index](++n);
}

void main()
{
    actions[0] = &Action0;
    actions[1] = 0; //Not used
    actions[2] = &Action1;

    actions[2](0);
}