任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
经过一些修改,我想出了这个:
template<int n>
class Printer
{
public:
Printer()
{
std::cout << (n + 1) << std::endl;
mNextPrinter.reset(new NextPrinter);
}
private:
typedef Printer<n + 1> NextPrinter;
std::auto_ptr<NextPrinter> mNextPrinter;
};
template<>
class Printer<1000>
{
};
int main()
{
Printer<0> p;
return 0;
}
后来@ybungalobill的作品启发我想出了这个更简单的版本:
struct NumberPrinter
{
NumberPrinter()
{
static int fNumber = 1;
std::cout << fNumber++ << std::endl;
}
};
int main()
{
NumberPrinter n[1000];
return 0;
}
其他回答
假设程序以通常的方式(./a.out)运行,因此它有一个参数,并忽略编译器类型警告,那么:
#include <stdio.h>
#include <stdlib.h>
void main(int i) {
static void (*cont[2])(int) = { main, exit };
printf("%d\n", i);
cont[i/1000](i+1);
}
#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;
}
#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);
}
使用指针算术,我们可以将数组自动初始化为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;
}
编辑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;
}