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

用C或c++怎么做呢?


当前回答

我认为这些代码工作完全正确,很容易理解,你可以打印任何像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();
}

其他回答

你可以非常简单地使用递归和强制错误…

另外,请原谅我的c++代码非常草率。

void print_number(uint number)
{
    try
    {
        print_number(number-1);
    }
    catch(int e) {}
    printf("%d", number+1);
}

void main()
{
    print_number(1001);
}
#include <stdio.h>
int main(int argc, char** argv)
{
printf("numbers from 1 to 1000\n");
}

这只使用O(log N)堆栈,并使用麦卡锡评估http://en.wikipedia.org/wiki/Short-circuit_evaluation作为其递归条件。

#include <stdio.h>

int printN(int n) {
  printf("%d\n", n);
  return 1;
}

int print_range(int low, int high) {
  return ((low+1==high) && (printN(low)) ||
      (print_range(low,(low+high)/2) && print_range((low+high)/2, high)));
}

int main() {
  print_range(1,1001);
}

如果POSIX解决方案被接受:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>

static void die(int sig) {
    exit(0);
}

static void wakeup(int sig) {
    static int counter = 1;
    struct itimerval timer;
    float i = 1000 / (1000 - counter);

    printf("%d\n", counter++);

    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 0;
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = i; /* Avoid code elimination */
    setitimer(ITIMER_REAL, &timer, 0);
}

int main() {
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    signal(SIGFPE, die);
    signal(SIGALRM, wakeup);
    wakeup(0);
    pthread_mutex_lock(&mutex);
    pthread_mutex_lock(&mutex); /* Deadlock, YAY! */
    return 0;
}

这是我的两个解。第一个是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);
}