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

用C或c++怎么做呢?


当前回答

我通读了所有这些答案,我的答案与其他答案不同。它是标准C语言,使用整数除法从数组中选择函数指针。此外,它在没有警告的情况下正确编译和执行,甚至在没有警告的情况下传递“夹板”。

当然,我也受到了很多其他答案的启发。即便如此,我的更好。

#include <stdio.h>
#include <stdlib.h>

static int x(/*@unused@*/ const char * format, ...) { exit(0); }

static void p(int v, int e) {
    static int (*a[])(const char *, ...) = { printf, x };
    (void)a[v/(e+1)]("%d\n", v);
    p(v+1, e);
}

int main(void) {
    p(1, 1000);
    return 0;
}

其他回答

我不打算写代码,只写想法。让一个线程每秒打印一个数字,然后另一个线程在1000秒后杀死第一个线程怎么样?

注:第一个线程通过递归生成数字。

Manglesky的解决方案很棒,但还不够模糊。: -):

#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d\n", i++);))) return 0; }

注意:

请期待取得成果。 这个程序经常出错。

Then

#include <iostream>
#include <ctime>

#ifdef _WIN32
#include <windows.h>
#define sleep(x) Sleep(x*1000)
#endif

int main() {
  time_t c = time(NULL);
retry:
  sleep(1);
  std::cout << time(NULL)-c << std::endl;
goto retry;
}

到目前为止,由于堆栈溢出,有很多不正常的退出,但还没有堆,所以这里是我的贡献:

#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(我认为有人这样做了),等等。

编辑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;
}