任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
立足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
其他回答
函数指针(ab)使用。没有预处理器的魔力来增加输出。ANSI C。
#include <stdio.h>
int i=1;
void x10( void (*f)() ){
f(); f(); f(); f(); f();
f(); f(); f(); f(); f();
}
void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }
int main(){
M();
}
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++概念,传承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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void(*word)(int);
word words[1024];
void print(int i) {
printf("%d\n", i);
words[i+1](i+1);
}
void bye(int i) {
exit(0);
}
int main(int argc, char *argv[]) {
words[0] = print;
words[1] = print;
memcpy(&words[2], &words[0], sizeof(word) * 2); // 0-3
memcpy(&words[4], &words[0], sizeof(word) * 4); // 0-7
memcpy(&words[8], &words[0], sizeof(word) * 8); // 0-15
memcpy(&words[16], &words[0], sizeof(word) * 16); // 0-31
memcpy(&words[32], &words[0], sizeof(word) * 32); // 0-63
memcpy(&words[64], &words[0], sizeof(word) * 64); // 0-127
memcpy(&words[128], &words[0], sizeof(word) * 128); // 0-255
memcpy(&words[256], &words[0], sizeof(word) * 256); // 0-511
memcpy(&words[512], &words[0], sizeof(word) * 512); // 0-1023
words[1001] = bye;
words[1](1);
}
system("/usr/bin/env echo {1..1000}");