任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void (*f[2])(int v);
void p(int v)
{
printf("%d\n", v++);
f[(int)(floor(pow(v, v - 1000)))](v);
}
void e(int v)
{
printf("%d\n", v);
}
int main(void)
{
f[0] = p;
f[1] = e;
p(1);
}
其他回答
注意:
请期待取得成果。 这个程序经常出错。
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;
}
我觉得这个答案会很简单,很容易理解。
int print1000(int num=1)
{
printf("%d\n", num);
// it will check first the num is less than 1000.
// If yes then call recursive function to print
return num<1000 && print1000(++num);
}
int main()
{
print1000();
return 0;
}
我通读了所有这些答案,我的答案与其他答案不同。它是标准C语言,使用整数除法从数组中选择函数指针。此外,它在没有警告的情况下正确编译和执行,甚至在没有警告的情况下传递“夹板”。
当然,我也受到了很多其他答案的启发。即便如此,我的更好。
#include <stdio.h>
#include <stdlib.h>
static int x(/*@unused@*/ const char * format, ...) { exit(0); }
static void p(int v, int e) {
static int (*a[])(const char *, ...) = { printf, x };
(void)a[v/(e+1)]("%d\n", v);
p(v+1, e);
}
int main(void) {
p(1, 1000);
return 0;
}
Manglesky的解决方案很棒,但还不够模糊。: -):
#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d\n", i++);))) return 0; }
也许这太明显和容易遵循,但这是标准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;
}