任务:打印从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;
}
我觉得好脏;我想我现在要去洗澡了。
其他回答
显然需要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);
}
一个脏代码:s
使用xor和数组的函数指针。
#include <stdio.h>
#include <stdlib.h>
typedef void (*fn)(int);
int lst[1001];
void print (int n)
{
printf ("%d ", n+1);
go (n+1);
}
void go (int n)
{
((fn)(((long)print)^((long)lst[n])))(n);
}
int main ()
{
lst[1000] = ((long)print)^((long)exit);
go (0);
}
简单C版本,在1000处终止:
int print_stuff(int count) {
printf("%d\n", count);
return (count ^ 1000) && print_stuff(count+1);
}
int main(int argc, char *argv[]) {
print_stuff(1);
return 0;
}
下面是一个使用setjmp/longjmp的版本,因为必须有人这样做:
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
void print(int i) {
printf("%d\n", i);
}
typedef void (*func_t)(int);
int main() {
jmp_buf buf;
func_t f[] = {print, exit};
int i = setjmp(buf)+1;
f[i/1001](i);
longjmp(buf, i);
return 0;
}
立足c++概念,传承gcc、vc
[root@localhost ~]# cat 1.cpp
#include <stdio.h>
#include <stdlib.h>
int i = 1;
void print(int arg0)
{
printf("%d ",i);
*(&arg0 - 1) = (int)print;
*(&arg0 - i/1000) = (int)exit;
i++;
}
int main(void) {
int a[1000];
print(0);
return 0;
}
运行:
[root@localhost ~]# g++ 1.cpp -o 1
[root@localhost ~]# ./1
1 2 ... 1000