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

用C或c++怎么做呢?


当前回答

未经测试,但应该是香草标准C:

void yesprint(int i);
void noprint(int i);

typedef void(*fnPtr)(int);
fnPtr dispatch[] = { noprint, yesprint };

void yesprint(int i) {
    printf("%d\n", i);
    dispatch[i < 1000](i + 1);
}

void noprint(int i) { /* do nothing. */ }

int main() {
    yesprint(1);
}

其他回答

立足c++概念,传承gcc、vc

[root@localhost ~]# cat 1.cpp
#include <stdio.h>
#include <stdlib.h>

int i = 1;
void print(int arg0)
{
    printf("%d ",i);
    *(&arg0 - 1) = (int)print;
    *(&arg0 - i/1000) = (int)exit;
    i++;
}
int main(void) {
    int a[1000];
    print(0);
    return 0;
}

运行:

[root@localhost ~]# g++ 1.cpp -o 1
[root@localhost ~]# ./1

1 2 ... 1000

令人惊讶的是,如果你放弃了“必须是C或c++”的要求,事情会变得多么简单:

Unix shell:

echo {1..1000} | tr ' ' '\n'

or

yes | nl | awk '{print $1}' | head -1000

如果你在一个没有yes命令的Unix变体上运行,使用其他进程至少生成1000行:

find / 2> /dev/null | nl | awk '{print $1}' | head -1000

or

cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000

or

head -1000 /etc/termcap | nl -s: | cut -d: -f1

您可以使用System()打印1到1000(通过使用DOS命令)

 include <process.h>
 void main()
 {
     system("cmd.exe /c for /l %x in (1, 1, 1000) do echo %x" );
 }

运行程序的.exe(可执行)文件,显示1到1000

注意:在WINDOWS中测试

一个脏代码: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);
}

假设程序以通常的方式(./a.out)运行,因此它有一个参数,并忽略编译器类型警告,那么:

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

void main(int i) {
    static void (*cont[2])(int) = { main, exit };
    printf("%d\n", i);
    cont[i/1000](i+1);
}