任务:打印从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();
}
其他回答
显然需要Windows/Visual Studio…但它确实有效。
#include <stdio.h>
#include <Windows.h>
void print(int x)
{
int y;
printf("%d\n", x);
__try
{
y = 1 / (x - 1000);
print(x + 1);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return;
}
}
void main()
{
print(1);
}
堆栈溢出:
#include <stdio.h>
static void print_line(int i)
{
printf("%d\n", i);
print_line(i+1);
}
int main(int argc, char* argv[])
{
//get up near the stack limit
char tmp[ 8388608 - 32 * 1000 - 196 * 32 ];
print_line(1);
}
这是一个8MB的堆栈。每次函数调用大约占用32个字节(因此是32 * 1000)。但是当我运行它时,我只得到804(因此是196 * 32;也许C运行时在堆栈中有其他部分,你也必须扣除)。
编译时递归!: P
#include <iostream>
template<int N>
struct NumberGeneration{
static void out(std::ostream& os)
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
};
template<>
struct NumberGeneration<1>{
static void out(std::ostream& os)
{
os << 1 << std::endl;
}
};
int main(){
NumberGeneration<1000>::out(std::cout);
}
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Printer
{
public:
Printer() { cout << ++i_ << "\n"; }
private:
static unsigned i_;
};
unsigned Printer::i_ = 0;
int main()
{
Printer p[1000];
}
你可以使用递归。
是这样的:
void Print(int n)
{
cout<<n<<" ";
if(n>1000)
return
else
return Print(n+1)
}
int main ()
{
Print(1);
}