任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
和这里的其他人相比有点无聊,但可能是他们想要的。
#include <stdio.h>
int f(int val) {
--val && f(val);
return printf( "%d\n", val+1);
}
void main(void) {
f(1000);
}
其他回答
和这里的其他人相比有点无聊,但可能是他们想要的。
#include <stdio.h>
int f(int val) {
--val && f(val);
return printf( "%d\n", val+1);
}
void main(void) {
f(1000);
}
受到Orion_G的回答和reddit讨论的启发;使用函数指针和二进制算术:
#include <stdio.h>
#define b10 1023
#define b3 7
typedef void (*fp) (int,int);
int i = 0;
void print(int a, int b) { printf("%d\n",++i); }
void kick(int a, int b) { return; }
void rec(int,int);
fp r1[] = {print, rec} ,r2[] = {kick, rec};
void rec(int a, int b) {
(r1[(b>>1)&1])(b10,b>>1);
(r2[(a>>1)&1])(a>>1,b);
}
int main() {
rec(b10,b3);
return 1;
}
c++利用RAII
#include <iostream>
using namespace std;
static int i = 1;
struct a
{
a(){cout<<i++<<endl;}
~a(){cout<<i++<<endl;}
}obj[500];
int main(){return 0;}
C语言开发宏
#include <stdio.h>
#define c1000(x) c5(c5(c5(c4(c2(x)))))
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x)) //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x
int main(int i){c1000(printf("%d\n",i++);)return 0;}
编辑:还有一个,这个很简单
#include <stdio.h>
#define p10(x) x x x x x x x x x x
int main(int i){p10(p10(p10(printf("%d\n",i++);)))return 0;}
解析:选C
编辑:此c代码包含<=和?:操作符
#include <stdio.h>
int main(int i){return (i<=1000)?main(printf("%d\n",i++)*0 + i):0;}
#include <stdio.h>
#define Out(i) printf("%d\n", i++);
#define REP(N) N N N N N N N N N N
#define Out1000(i) REP(REP(REP(Out(i))));
void main()
{
int i = 1;
Out1000(i);
}
更多的预处理程序滥用:
#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;
}
我觉得好脏;我想我现在要去洗澡了。