任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
Javascript是为了好玩。包括自动停止在1000:
var max = 1000;
var b = ["break"];
function increment(i) {
var j = Math.abs(i - max);
console.log(j);
b[(i/i) - 1].toString();
i--;
increment(i);
}
increment(max);
其他回答
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }
这就像另一个以“愤怒”结尾的英语单词谜语,对吧?
以下是我知道的三个解决方案。不过,第二种说法可能存在争议。
// compile time recursion
template<int N> void f1()
{
f1<N-1>();
cout << N << '\n';
}
template<> void f1<1>()
{
cout << 1 << '\n';
}
// short circuiting (not a conditional statement)
void f2(int N)
{
N && (f2(N-1), cout << N << '\n');
}
// constructors!
struct A {
A() {
static int N = 1;
cout << N++ << '\n';
}
};
int main()
{
f1<1000>();
f2(1000);
delete[] new A[1000]; // (3)
A data[1000]; // (4) added by Martin York
}
[编辑:(1)和(4)只能用于编译时常数,(2)和(3)也可以用于运行时表达式-结束编辑。]]
编辑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;
}
易如反掌!: P
#include <iostream>
static int current = 1;
struct print
{
print() { std::cout << current++ << std::endl; }
};
int main()
{
print numbers [1000];
}
预处理程序滥用!
#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)非常有趣。