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

用C或c++怎么做呢?


当前回答

将1到1000放入文件file中

int main()
{
    system("cat file");
    return 0;
 }

其他回答

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

我假设,由于这个问题的性质,扩展是不排除的?

而且,我很惊讶,到目前为止还没有人去。

int main () {
    int i = 0;
    void * addr[1001] = { [0 ... 999] = &&again};
    addr[1000] = &&end;
again:
    printf("%d\n", i + 1);
    goto *addr[++i];
end:
    return 0;
}

好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)

函数指针(ab)使用。没有预处理器的魔力来增加输出。ANSI C。

#include <stdio.h>

int i=1;

void x10( void (*f)() ){
    f(); f(); f(); f(); f();
    f(); f(); f(); f(); f();
}

void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }

int main(){
    M();
}
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }

这就像另一个以“愤怒”结尾的英语单词谜语,对吧?

下面是使用信号的POSIX变体:

#include <stdio.h>
#include <signal.h>

void counter(int done)
{
        static int i;

        done = ++i / 1000;

        printf("%d\n", i);

        signal(SIGINT, (void (*)(int))(done * (int)SIG_DFL + (1-done) * (int)&counter));
        raise(SIGINT);
}

int main()
{
        signal(SIGINT, &counter);
        raise(SIGINT);

        return 0;
}

有趣的部分是counter()对signal()的调用。在这里,将安装一个新的信号处理程序:如果"done"为真,则SIG_DFL,否则计数器。

为了使这个解决方案更加可笑,我使用了信号处理程序所需的int形参来保存临时计算的结果。作为一个副作用,恼人的“未使用变量”警告在使用gcc -W -Wall编译时消失。