任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
函数指针(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();
}
其他回答
#include <stdio.h>
int i = 0;
p() { printf("%d\n", ++i); }
a() { p();p();p();p();p(); }
b() { a();a();a();a();a(); }
c() { b();b();b();b();b(); }
main() { c();c();c();c();c();c();c();c(); return 0; }
我很惊讶似乎没有人张贴这个——我认为这是最明显的方式。1000 = 5*5*5*8。
立足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 <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);
}
使用指针算术,我们可以将数组自动初始化为0。
#include <stdio.h>
void func();
typedef void (*fpa)();
fpa fparray[1002] = { 0 };
int x = 1;
void func() {
printf("%i\n", x++);
((long)fparray[x] + &func)();
}
void end() { return; }
int main() {
fparray[1001] = (fpa)(&end - &func);
func();
return 0;
}
如果你的C编译器支持block,那么你可以这样写:
#include <stdio.h>
void ten(void (^b)(void)) { b();b();b();b();b();b();b();b();b();b(); }
int main() {
__block int i = 0;
ten(^{
ten(^{
ten(^{
printf("%d\n", ++i);
});
});
});
return 0;
}