任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
使用宏压缩:
#include <stdio.h>
#define a printf("%d ",++i);
#define b a a a a a
#define c b b b b b
#define d c c c c c
#define e d d d d
int main ( void ) {
int i = 0;
e e
return 0;
}
或者更好:
#include <stdio.h>
#define a printf("%d ",++i);
#define r(x) x x x x x
#define b r(r(r(a a a a)))
int main ( void ) {
int i = 0;
b b
return 0;
}
其他回答
使用系统命令:
system("/usr/bin/seq 1000");
经过一些修改,我想出了这个:
template<int n>
class Printer
{
public:
Printer()
{
std::cout << (n + 1) << std::endl;
mNextPrinter.reset(new NextPrinter);
}
private:
typedef Printer<n + 1> NextPrinter;
std::auto_ptr<NextPrinter> mNextPrinter;
};
template<>
class Printer<1000>
{
};
int main()
{
Printer<0> p;
return 0;
}
后来@ybungalobill的作品启发我想出了这个更简单的版本:
struct NumberPrinter
{
NumberPrinter()
{
static int fNumber = 1;
std::cout << fNumber++ << std::endl;
}
};
int main()
{
NumberPrinter n[1000];
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;
}
编译时递归!: P
#include <iostream>
template<int N>
struct NumberGeneration{
static void out(std::ostream& os)
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
};
template<>
struct NumberGeneration<1>{
static void out(std::ostream& os)
{
os << 1 << std::endl;
}
};
int main(){
NumberGeneration<1000>::out(std::cout);
}
以下是我知道的三个解决方案。不过,第二种说法可能存在争议。
// compile time recursion
template<int N> void f1()
{
f1<N-1>();
cout << N << '\n';
}
template<> void f1<1>()
{
cout << 1 << '\n';
}
// short circuiting (not a conditional statement)
void f2(int N)
{
N && (f2(N-1), cout << N << '\n');
}
// constructors!
struct A {
A() {
static int N = 1;
cout << N++ << '\n';
}
};
int main()
{
f1<1000>();
f2(1000);
delete[] new A[1000]; // (3)
A data[1000]; // (4) added by Martin York
}
[编辑:(1)和(4)只能用于编译时常数,(2)和(3)也可以用于运行时表达式-结束编辑。]]