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

用C或c++怎么做呢?


当前回答

Javascript是为了好玩。包括自动停止在1000:

var max = 1000;
var b = ["break"];
function increment(i) {
    var j = Math.abs(i - max);
    console.log(j);           
    b[(i/i) - 1].toString();
    i--;
    increment(i);    
}
increment(max);

其他回答

也许这太明显和容易遵循,但这是标准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;
}

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

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

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

你可以使用递归。

是这样的:

void Print(int n)
{
  cout<<n<<" ";   
  if(n>1000)
     return
  else
     return Print(n+1)
}    

int main ()
{
  Print(1);
}

令人惊讶的是,如果你放弃了“必须是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
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);