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

用C或c++怎么做呢?


当前回答

#include <stdio.h>
#include <assert.h>

void foo( int n )
{
 printf("%d\n", n);
 assert( n > 0 );
 foo(--n); 
}

int main()
{
 foo( 1000 );
 getchar();
}

其他回答

template <int remaining>
void print(int v) {
 printf("%d\n", v);
 print<remaining-1>(v+1);
}

template <>
void print<0>(int v) {
}

print<1000>(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 <stdio.h>
#define Out(i)       printf("%d\n", i++);
#define REP(N)       N N N N N N N N N N
#define Out1000(i)   REP(REP(REP(Out(i))));
void main()
{
 int i = 1;
 Out1000(i);
}

不懂足够的C(++)来写代码,但你可以使用递归而不是循环。为了避免这种情况,可以使用在第1000次访问后抛出异常的数据结构。例如,某种带有范围检查的列表,在每次递归时增加/减少索引。

从评论中判断,c++中似乎没有任何范围检查列表?

相反,你可以用1/n作为递归函数的参数,每次调用都减少1。从1000开始。DivisionByZero异常将停止递归

这只使用O(log N)堆栈,并使用麦卡锡评估http://en.wikipedia.org/wiki/Short-circuit_evaluation作为其递归条件。

#include <stdio.h>

int printN(int n) {
  printf("%d\n", n);
  return 1;
}

int print_range(int low, int high) {
  return ((low+1==high) && (printN(low)) ||
      (print_range(low,(low+high)/2) && print_range((low+high)/2, high)));
}

int main() {
  print_range(1,1001);
}