任务:打印从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];
}
其他回答
#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++编译器中:所有元素都是由默认构造函数创建的 然后被复制构造函数复制。
如果你的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;
}
注意:
请期待取得成果。 这个程序经常出错。
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;
}
一个脏代码:s
使用xor和数组的函数指针。
#include <stdio.h>
#include <stdlib.h>
typedef void (*fn)(int);
int lst[1001];
void print (int n)
{
printf ("%d ", n+1);
go (n+1);
}
void go (int n)
{
((fn)(((long)print)^((long)lst[n])))(n);
}
int main ()
{
lst[1000] = ((long)print)^((long)exit);
go (0);
}
使用系统命令:
system("/usr/bin/seq 1000");