任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从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();
}
其他回答
使用递归,可以使用函数指针算术替换条件:
#include <stdio.h>
#include <stdlib.h> // for: void exit(int CODE)
// function pointer
typedef void (*fptr)(int);
void next(int n)
{
printf("%d\n", n);
// pointer to next function to call
fptr fp = (fptr)(((n != 0) * (unsigned int) next) +
((n == 0) * (unsigned int) exit));
// decrement and call either ``next'' or ``exit''
fp(n-1);
}
int main()
{
next(1000);
}
注意,这里没有条件句;n !=0和n==0是无分支操作。(不过,我们在尾部调用中执行了一个分支)。
看起来它不需要使用循环
printf("1 10 11 100 101 110 111 1000\n");
system("/usr/bin/env echo {1..1000}");
你可以使用递归。
是这样的:
void Print(int n)
{
cout<<n<<" ";
if(n>1000)
return
else
return Print(n+1)
}
int main ()
{
Print(1);
}
这个实际上编译为没有任何条件的程序集:
#include <stdio.h>
#include <stdlib.h>
void main(int j) {
printf("%d\n", j);
(&main + (&exit - &main)*(j/1000))(j+1);
}
编辑:添加了'&',因此它将考虑地址,从而避免指针错误。
上面的这个版本在标准C中,因为它不依赖于函数指针的算术:
#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);
}