任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
更多的预处理程序滥用:
#include <stdio.h>
#define A1(x,y) #x #y "0\n" #x #y "1\n" #x #y "2\n" #x #y "3\n" #x #y "4\n" #x #y "5\n" #x #y "6\n" #x #y "7\n" #x #y "8\n" #x #y "9\n"
#define A2(x) A1(x,1) A1(x,2) A1(x,3) A1(x,4) A1(x,5) A1(x,6) A1(x,7) A1(x,8) A1(x,9)
#define A3(x) A1(x,0) A2(x)
#define A4 A3(1) A3(2) A3(3) A3(4) A3(5) A3(6) A3(7) A3(8) A3(9)
#define A5 "1\n2\n3\n4\n5\n6\n7\n8\n9\n" A2() A4 "1000\n"
int main(int argc, char *argv[]) {
printf(A5);
return 0;
}
我觉得好脏;我想我现在要去洗澡了。
其他回答
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>
int main()
{
boost::mpl::for_each<boost::mpl::range_c<unsigned, 1, 1001> >(std::cout << boost::lambda::_1 << '\n');
return(0);
}
这个实际上编译为没有任何条件的程序集:
#include <stdio.h>
#include <stdlib.h>
void main(int j) {
printf("%d\n", j);
(&main + (&exit - &main)*(j/1000))(j+1);
}
编辑:添加了'&',因此它将考虑地址,从而避免指针错误。
上面的这个版本在标准C中,因为它不依赖于函数指针的算术:
#include <stdio.h>
#include <stdlib.h>
void f(int j)
{
static void (*const ft[2])(int) = { f, exit };
printf("%d\n", j);
ft[j/1000](j + 1);
}
int main(int argc, char *argv[])
{
f(1);
}
我觉得这个答案会很简单,很容易理解。
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;
}
显然需要Windows/Visual Studio…但它确实有效。
#include <stdio.h>
#include <Windows.h>
void print(int x)
{
int y;
printf("%d\n", x);
__try
{
y = 1 / (x - 1000);
print(x + 1);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return;
}
}
void main()
{
print(1);
}
如果您不介意前导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())