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

用C或c++怎么做呢?


当前回答

#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);
}

其他回答

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

class Printer
{
public:
 Printer() { cout << ++i_ << "\n"; }
private:
 static unsigned i_;
};

unsigned Printer::i_ = 0;

int main()
{
 Printer p[1000];
}
#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++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。

下面是使用信号的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编译时消失。

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

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

正如它是回答:)

在不使用任何循环或条件语句的情况下,从1到1000的数字。不要只写printf()或cout语句1000次。”);