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

用C或c++怎么做呢?


当前回答

我想知道面试官是不是说错了一个问题:不使用循环,计算从1到1000(或从n到m的任意数字)的和。它还教会我们如何分析问题。在C中从1到1000s打印#s总是依赖于在生产程序中可能不会使用的技巧(Main中的尾部递归,计算真实性的副作用,或预处理和模板技巧)。

这将是一个很好的抽查,看看你是否接受过数学训练,因为关于高斯和他的解的古老故事可能对任何接受过数学训练的人都很熟悉。

其他回答

显然需要Windows/Visual Studio…但它确实有效。

#include <stdio.h>
#include <Windows.h>

void print(int x)
{
    int y;

    printf("%d\n", x);
    __try
    {
        y = 1 / (x - 1000);
        print(x + 1);
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        return;
    }
}

void main()
{
    print(1);
}

预处理程序滥用!

#include <stdio.h>

void p(int x) { printf("%d\n", x); }

#define P5(x) p(x); p(x+1); p(x+2); p(x+3); p(x+4);
#define P25(x) P5(x) P5(x+5) P5(x+10) P5(x+15) P5(x+20)
#define P125(x) P25(x) P25(x+50) P25(x+75) P25(x+100)
#define P500(x) P125(x) P125(x+125) P125(x+250) P125(x+375)

int main(void)
{
  P500(1) P500(501)
  return 0;
}

预处理程序(参见gcc -E input.c)非常有趣。

堆栈溢出:

#include <stdio.h>

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

int main(int argc, char* argv[])
{   
 //get up near the stack limit
 char tmp[ 8388608 - 32 * 1000 - 196 * 32 ];
 print_line(1);
} 

这是一个8MB的堆栈。每次函数调用大约占用32个字节(因此是32 * 1000)。但是当我运行它时,我只得到804(因此是196 * 32;也许C运行时在堆栈中有其他部分,你也必须扣除)。

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

#include <stdio.h>

int show(int i) {
   printf("%d\n",i);
   return( (i>=1000) || show(i+1));
}


int main(int argc,char **argv) {
   return show(1);
}

||操作符使递归调用短路,以显示i为>= 1000时的情况。