任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
更多的预处理程序滥用:
#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;
}
我觉得好脏;我想我现在要去洗澡了。
其他回答
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 "stdafx.h"
static n=1;
class number {
public:
number () {
std::cout << n++ << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
number X[1000];
return 0;
}
template <int To, int From = 1>
struct printer {
static void print() {
cout << From << endl;
printer<To, From + 1>::print();
}
};
template <int Done>
struct printer<Done, Done> {
static void print() {
cout << Done << endl;
}
};
int main()
{
printer<1000>::print();
}
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void (*f[2])(int v);
void p(int v)
{
printf("%d\n", v++);
f[(int)(floor(pow(v, v - 1000)))](v);
}
void e(int v)
{
printf("%d\n", v);
}
int main(void)
{
f[0] = p;
f[1] = e;
p(1);
}
只需使用std::copy()和一个特殊的迭代器。
#include <algorithm>
#include <iostream>
#include <iterator>
struct number_iterator
{
typedef std::input_iterator_tag iterator_category;
typedef int value_type;
typedef std::size_t difference_type;
typedef int* pointer;
typedef int& reference;
number_iterator(int v): value(v) {}
bool operator != (number_iterator const& rhs) { return value != rhs.value;}
number_iterator operator++() { ++value; return *this;}
int operator*() { return value; }
int value;
};
int main()
{
std::copy(number_iterator(1),
number_iterator(1001),
std::ostream_iterator<int>(std::cout, " "));
}