任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <stdio.h>
void nothing(int);
void next(int);
void (*dispatch[2])(int) = {next, nothing};
void nothing(int x) { }
void next(int x)
{
printf("%i\n", x);
dispatch[x/1000](x+1);
}
int main()
{
next(1);
return 0;
}
其他回答
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); 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;
}
#include<iostream>
#include<stdexcept>
using namespace std;
int main(int arg)
{
try
{
printf("%d\n",arg);
int j=1/(arg-1000);
main(arg+1);
}
catch(...)
{
exit(1);
}
}
#include <stdio.h>
void nothing(int);
void next(int);
void (*dispatch[2])(int) = {next, nothing};
void nothing(int x) { }
void next(int x)
{
printf("%i\n", x);
dispatch[x/1000](x+1);
}
int main()
{
next(1);
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; }