任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
易如反掌!: P
#include <iostream>
static int current = 1;
struct print
{
print() { std::cout << current++ << std::endl; }
};
int main()
{
print numbers [1000];
}
其他回答
OpenMP版本(当然是非有序的):
#include <iostream>
#include <omp.h>
int main(int argc, char** argv)
{
#pragma omp parallel num_threads(1000)
{
#pragma omp critical
{
std::cout << omp_get_thread_num() << std::endl;
}
}
return 0;
}
(不工作与VS2010 OpenMP运行时(限制为64线程),但工作在linux上,例如,英特尔编译器)
下面是一个有序的版本:
#include <stdio.h>
#include <omp.h>
int main(int argc, char *argv[])
{
int i = 1;
#pragma omp parallel num_threads(1000)
#pragma omp critical
printf("%d ", i++);
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++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。
#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];
}
再举一个异常终止的例子。这一次调整堆栈大小以在1000次递归时耗尽。
int main(int c, char **v)
{
static cnt=0;
char fill[12524];
printf("%d\n", cnt++);
main(c,v);
}
在我的机器上打印1到1000
995
996
997
998
999
1000
Segmentation fault (core dumped)
#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);
}