任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <stdio.h>
int main(int argc, char** argv)
{
printf("numbers from 1 to 1000\n");
}
其他回答
使用递归,可以使用函数指针算术替换条件:
#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是无分支操作。(不过,我们在尾部调用中执行了一个分支)。
显然需要Windows/Visual Studio…但它确实有效。
#include <stdio.h>
#include <Windows.h>
void print(int x)
{
int y;
printf("%d\n", x);
__try
{
y = 1 / (x - 1000);
print(x + 1);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return;
}
}
void main()
{
print(1);
}
触发致命错误!这是文件,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("1 10 11 100 101 110 111 1000\n");
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }
这就像另一个以“愤怒”结尾的英语单词谜语,对吧?