任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <iostream>
using namespace std;
template<int N>
void func()
{
func<N-1>();
cout << N << "\t";
}
template<>
void func<1>()
{
cout << 1 << "\t";
}
int main()
{
func<1000>();
cout << endl;
return 0;
}
其他回答
一个脏代码:s
使用xor和数组的函数指针。
#include <stdio.h>
#include <stdlib.h>
typedef void (*fn)(int);
int lst[1001];
void print (int n)
{
printf ("%d ", n+1);
go (n+1);
}
void go (int n)
{
((fn)(((long)print)^((long)lst[n])))(n);
}
int main ()
{
lst[1000] = ((long)print)^((long)exit);
go (0);
}
我觉得这个答案会很简单,很容易理解。
int print1000(int num=1)
{
printf("%d\n", num);
// it will check first the num is less than 1000.
// If yes then call recursive function to print
return num<1000 && print1000(++num);
}
int main()
{
print1000();
return 0;
}
我假设,由于这个问题的性质,扩展是不排除的?
而且,我很惊讶,到目前为止还没有人去。
int main () {
int i = 0;
void * addr[1001] = { [0 ... 999] = &&again};
addr[1000] = &&end;
again:
printf("%d\n", i + 1);
goto *addr[++i];
end:
return 0;
}
好吧,所以从技术上讲它是一个循环-但它并不比目前为止所有递归的例子更循环;)
你可以使用递归。
是这样的:
void Print(int n)
{
cout<<n<<" ";
if(n>1000)
return
else
return Print(n+1)
}
int main ()
{
Print(1);
}
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();
}