任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
显然需要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);
}
其他回答
我们可以启动1000个线程,每个线程打印一个数字。安装OpenMPI,使用mpicxx -o 1000 1000.cpp编译,然后使用mpirun -np 1000. /1000运行。您可能需要使用limit或ulimit来增加描述符限制。注意,这将是相当慢的,除非您有大量的核心!
#include <cstdio>
#include <mpi.h>
using namespace std;
int main(int argc, char **argv) {
MPI::Init(argc, argv);
cout << MPI::COMM_WORLD.Get_rank() + 1 << endl;
MPI::Finalize();
}
当然,这些数字不一定是按顺序打印的,但这个问题并不要求它们是有序的。
printf("%d\n", 2);
printf("%d\n", 3);
它不会打印所有的数字,但它会“打印从1到1000的数字”。暧昧的问题求赢!:)
#include <stdio.h>
int i = 0;
p() { printf("%d\n", ++i); }
a() { p();p();p();p();p(); }
b() { a();a();a();a();a(); }
c() { b();b();b();b();b(); }
main() { c();c();c();c();c();c();c();c(); return 0; }
我很惊讶似乎没有人张贴这个——我认为这是最明显的方式。1000 = 5*5*5*8。
使用递归,可以使用函数指针算术替换条件:
#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是无分支操作。(不过,我们在尾部调用中执行了一个分支)。
system("/usr/bin/env echo {1..1000}");