打印1至1000没有循环或条件语句 [英] Printing 1 to 1000 without loop or conditionals

查看:122
本文介绍了打印1至1000没有循环或条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

工作:打印编号从1到1000,而无需使用任何循环或条件语句。不要只写的printf() COUT 语句1000次。

Task: Print numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.

你会怎么做,使用C或C ++?

How would you do that using C or C++?

推荐答案

这人真正编译成汇编了没有任何条件语句:

This one actually compiles to assembly that doesn't have any conditionals:

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

void main(int j) {
  printf("%d\n", j);
  (&main + (&exit - &main)*(j/1000))(j+1);
}



编辑:新增'和;'所以它会考虑因此而回避地址指针错误。


Added '&' so it will consider the address hence evading the pointer errors.

这个版本在标准C以上的,因为它不依赖于算术函数指针:

This version of the above in standard C, since it doesn't rely on arithmetic on function pointers:

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

void f(int j)
{
    static void (*const ft[2])(int) = { f, exit };

    printf("%d\n", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
    f(1);
}

这篇关于打印1至1000没有循环或条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆