任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。

用C或c++怎么做呢?


当前回答

如果你打算使用编译时递归,那么你可能还想使用分治法来避免触及模板深度限制:

#include <iostream>

template<int L, int U>
struct range
{
    enum {H = (L + U) / 2};
    static inline void f ()
    {
        range<L, H>::f ();
        range<H+1, U>::f ();
    }
};

template<int L>
struct range<L, L>
{
    static inline void f ()
    {
        std::cout << L << '\n';
    }
};

int main (int argc, char* argv[])
{
    range<1, 1000>::f ();
    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);
}

将1到1000放入文件file中

int main()
{
    system("cat file");
    return 0;
 }

我认为这些代码工作完全正确,很容易理解,你可以打印任何像1到100或1到最终范围。把它放在I中,然后转移到call function中。

int main()
{
    int i=1;
    call(i,i);
}

void call(int i,int j)
{
    printf("%d",i);
    sleep(1); // to see the numbers for delay
    j /= (j-1000);

    j = ++i;

    call(i,j);
}

所以当j等于1000时,它会被除零,然后直接退出程序这就是我打印数字的想法

或者更简单的代码..

int main()
{
    static int i = 1;
    static int j = 1;
    printf("%d", i);
    sleep(1);
    j = ++i;
    j /= (j-1000);
    main();
}
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 <cstdio>
#include <cstdlib>
#include <sys/mman.h>
#include <sys/signal.h>
#define PAGE_SIZE 4096
void print_and_set(int i, int* s)
{
  *s = i;
  printf("%d\n", i);
  print_and_set(i + 1, s + 1);
}
void
sigsegv(int)
{
  fflush(stdout); exit(0);
}
int
main(int argc, char** argv)
{
  int* mem = reinterpret_cast<int*>
    (reinterpret_cast<char*>(mmap(NULL, PAGE_SIZE * 2, PROT_WRITE,
                                  MAP_PRIVATE | MAP_ANONYMOUS, 0, 0)) +
     PAGE_SIZE - 1000 * sizeof(int));
  mprotect(mem + 1000, PAGE_SIZE, PROT_NONE);
  signal(SIGSEGV, sigsegv);
  print_and_set(1, mem);
}

这不是很好的实践,也没有错误检查(原因很明显),但我不认为这是问题的重点!

当然,还有许多其他不正常的终止选项,其中一些更简单:assert()、SIGFPE(我认为有人这样做了),等等。