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

用C或c++怎么做呢?


当前回答

c++利用RAII

#include <iostream>
using namespace std;

static int i = 1;
struct a
{
    a(){cout<<i++<<endl;}
    ~a(){cout<<i++<<endl;}
}obj[500];

int main(){return 0;}

C语言开发宏

#include <stdio.h>

#define c1000(x) c5(c5(c5(c4(c2(x))))) 
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x))   //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x

int main(int i){c1000(printf("%d\n",i++);)return 0;}

编辑:还有一个,这个很简单

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

解析:选C

编辑:此c代码包含<=和?:操作符

#include <stdio.h>

int main(int i){return (i<=1000)?main(printf("%d\n",i++)*0 + i):0;}

其他回答

经过一些修改,我想出了这个:

template<int n>
class Printer
{
public:
    Printer()
    {        
        std::cout << (n + 1) << std::endl;
        mNextPrinter.reset(new NextPrinter);
    }

private:
    typedef Printer<n + 1> NextPrinter;
    std::auto_ptr<NextPrinter> mNextPrinter;
};

template<>
class Printer<1000>
{
};

int main()
{
    Printer<0> p;
    return 0;
}

后来@ybungalobill的作品启发我想出了这个更简单的版本:

struct NumberPrinter
{
    NumberPrinter()
    {
        static int fNumber = 1;
        std::cout << fNumber++ << std::endl;
    }
};


int main()
{
    NumberPrinter n[1000];
    return 0;
}

触发致命错误!这是文件,counup .c:

#include <stdio.h>
#define MAX 1000
int boom;
int foo(n) {
    boom = 1 / (MAX-n+1);
    printf("%d\n", n);
    foo(n+1);
}
int main() {
    foo(1);
}

编译,然后在shell提示符下执行:

$ ./countup
1
2
3
...
996
997
998
999
1000
Floating point exception
$

这确实打印了从1到1000的数字,没有任何循环或条件!

printf("%d\n", 2);
printf("%d\n", 3);

它不会打印所有的数字,但它会“打印从1到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;
    }
#include<iostream>
#include<stdexcept>

using namespace std;

int main(int arg)

{
    try

    {

        printf("%d\n",arg);
        int j=1/(arg-1000);
        main(arg+1);
    }

    catch(...)
    {
        exit(1);
    }
}