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

用C或c++怎么做呢?


当前回答

尽管在这里看到了所有出色的代码,但我认为唯一真正的答案是它不能实现。

为什么?简单。事实上,每一个答案都是循环的。隐藏为递归的循环仍然是循环。看一下汇编代码就会发现这一事实。即使读取和打印带有数字的文本文件也涉及循环。再看一下机器代码。输入1000个printf语句也意味着循环,因为printf本身也有循环。

不可能做到。

其他回答

立足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
    static void Main(string[] args)
    {
        print(1000);
        System.Console.ReadKey();
    }

    static bool print(int val)
    {
        try
        {
            print( ((val/val)*val) - 1);
            System.Console.WriteLine(val.ToString());
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }

这是我的两个解。第一个是c#,第二个是C语言:

C#:

const int limit = 1000;

Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n);  actions[Math.Sign(limit - n-1)](n + 1); };

actions[1](0);

C:

#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))

void (*actions[3])(int);

void Action0(int n)
{
    printf("%d", n);
}

void Action1(int n)
{
    int index;
    printf("%d\n", n);
    index = sign(998-n)+1;
    actions[index](++n);
}

void main()
{
    actions[0] = &Action0;
    actions[1] = 0; //Not used
    actions[2] = &Action1;

    actions[2](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);
}

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