任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
应该在任何不喜欢0 / 0的机器上工作。如果需要,可以用空指针引用替换它。程序可以在打印1到1000后失败,对吧?
#include <stdio.h>
void print_1000(int i);
void print_1000(int i) {
int j;
printf("%d\n", i);
j = 1000 - i;
j = j / j;
i++;
print_1000(i);
}
int main() {
print_1000(1);
}
其他回答
我觉得这个答案会很简单,很容易理解。
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;
}
编译时递归!: 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];
}
既不是循环语句也不是条件语句,至少它不会在我的机器上崩溃:)。使用一些指针魔法我们有。
#include <stdlib.h>
#include <stdio.h>
typedef void (*fp) (void *, int );
void end(fp* v, int i){
printf("1000\n");
return;
}
void print(fp *v, int i)
{
printf("%d\n", 1000-i);
v[i-1] = (fp)print;
v[0] = (fp)end;
(v[i-1])(v, i-1);
}
int main(int argc, char *argv[])
{
fp v[1000];
print(v, 1000);
return 0;
}
使用递归,可以使用函数指针算术替换条件:
#include <stdio.h>
#include <stdlib.h> // for: void exit(int CODE)
// function pointer
typedef void (*fptr)(int);
void next(int n)
{
printf("%d\n", n);
// pointer to next function to call
fptr fp = (fptr)(((n != 0) * (unsigned int) next) +
((n == 0) * (unsigned int) exit));
// decrement and call either ``next'' or ``exit''
fp(n-1);
}
int main()
{
next(1000);
}
注意,这里没有条件句;n !=0和n==0是无分支操作。(不过,我们在尾部调用中执行了一个分支)。