任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或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++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。
其他回答
没人说它不应该事后分段错误,对吧?
注意:这在我的64位Mac OS X系统上正常工作。对于其他系统,您需要将参数更改为setrlimit,并相应地更改spacecew的大小。: -)
(我不应该包括这个,但以防万一:这显然不是一个好的编程实践的例子。然而,它确实有一个优点,那就是它利用了这个网站的名称。)
#include <sys/resource.h>
#include <stdio.h>
void recurse(int n)
{
printf("%d\n", n);
recurse(n + 1);
}
int main()
{
struct rlimit rlp;
char spacechew[4200];
getrlimit(RLIMIT_STACK, &rlp);
rlp.rlim_cur = rlp.rlim_max = 40960;
setrlimit(RLIMIT_STACK, &rlp);
recurse(1);
return 0; /* optimistically */
}
#include<stdio.h>
int b=1;
int printS(){
printf("%d\n",b);
b++;
(1001-b) && printS();
}
int main(){printS();}
如果您不介意前导0,那么让我们跳过printf
#include <stdlib.h>
void l();
void n();
void (*c[3])() = {l, n, exit};
char *a;
void (*x)();
char b[] = "0000";
void run() { x(); run(); }
#define C(d,s,i,j,f) void d() { s;x = c[i]; a = j;f; }
C(l, puts(b), 1+(a<b), b+3,)
C(n, int v = *a - '0' + 1; *a = v%10 + '0', v/10, a-1,)
C(main,,1,b+3, run())
注意:
请期待取得成果。 这个程序经常出错。
Then
#include <iostream>
#include <ctime>
#ifdef _WIN32
#include <windows.h>
#define sleep(x) Sleep(x*1000)
#endif
int main() {
time_t c = time(NULL);
retry:
sleep(1);
std::cout << time(NULL)-c << std::endl;
goto retry;
}
如果你的C编译器支持block,那么你可以这样写:
#include <stdio.h>
void ten(void (^b)(void)) { b();b();b();b();b();b();b();b();b();b(); }
int main() {
__block int i = 0;
ten(^{
ten(^{
ten(^{
printf("%d\n", ++i);
});
});
});
return 0;
}