任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }
这就像另一个以“愤怒”结尾的英语单词谜语,对吧?
其他回答
更多的预处理程序滥用:
#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 <stdio.h>
void p(int x) { printf("%d\n", x); }
#define P5(x) p(x); p(x+1); p(x+2); p(x+3); p(x+4);
#define P25(x) P5(x) P5(x+5) P5(x+10) P5(x+15) P5(x+20)
#define P125(x) P25(x) P25(x+50) P25(x+75) P25(x+100)
#define P500(x) P125(x) P125(x+125) P125(x+250) P125(x+375)
int main(void)
{
P500(1) P500(501)
return 0;
}
预处理程序(参见gcc -E input.c)非常有趣。
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; }
#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);
}
编辑2:
我从代码中删除了未定义的行为。谢谢@sehe的通知。
没有循环,递归,条件和所有标准C…(qsort滥用):
#include <stdio.h>
#include <stdlib.h>
int numbers[51] = {0};
int comp(const void * a, const void * b){
numbers[0]++;
printf("%i\n", numbers[0]);
return 0;
}
int main()
{
qsort(numbers+1,50,sizeof(int),comp);
comp(NULL, NULL);
return 0;
}