任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
注意:
请期待取得成果。 这个程序经常出错。
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;
}
其他回答
以下是我知道的三个解决方案。不过,第二种说法可能存在争议。
// 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)也可以用于运行时表达式-结束编辑。]]
也许这太明显和容易遵循,但这是标准c++,不转储堆栈和运行在O(n)时间使用O(n)内存。
#include <iostream>
#include <vector>
using namespace std;
int main (int argc, char** args) {
vector<int> foo = vector<int>(1000);
int terminator = 0;
p:
cout << terminator << endl;
try {
foo.at(terminator++);
} catch(...) {
return 0;
}
goto p;
}
如果您不介意前导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())
printf("%d\n", 2);
printf("%d\n", 3);
它不会打印所有的数字,但它会“打印从1到1000的数字”。暧昧的问题求赢!:)
令人惊讶的是,如果你放弃了“必须是C或c++”的要求,事情会变得多么简单:
Unix shell:
echo {1..1000} | tr ' ' '\n'
or
yes | nl | awk '{print $1}' | head -1000
如果你在一个没有yes命令的Unix变体上运行,使用其他进程至少生成1000行:
find / 2> /dev/null | nl | awk '{print $1}' | head -1000
or
cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000
or
head -1000 /etc/termcap | nl -s: | cut -d: -f1