任务:打印从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();
}
当然,这些数字不一定是按顺序打印的,但这个问题并不要求它们是有序的。
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void (*f[2])(int v);
void p(int v)
{
printf("%d\n", v++);
f[(int)(floor(pow(v, v - 1000)))](v);
}
void e(int v)
{
printf("%d\n", v);
}
int main(void)
{
f[0] = p;
f[1] = e;
p(1);
}
下面是使用信号的POSIX变体:
#include <stdio.h>
#include <signal.h>
void counter(int done)
{
static int i;
done = ++i / 1000;
printf("%d\n", i);
signal(SIGINT, (void (*)(int))(done * (int)SIG_DFL + (1-done) * (int)&counter));
raise(SIGINT);
}
int main()
{
signal(SIGINT, &counter);
raise(SIGINT);
return 0;
}
有趣的部分是counter()对signal()的调用。在这里,将安装一个新的信号处理程序:如果"done"为真,则SIG_DFL,否则计数器。
为了使这个解决方案更加可笑,我使用了信号处理程序所需的int形参来保存临时计算的结果。作为一个副作用,恼人的“未使用变量”警告在使用gcc -W -Wall编译时消失。
编辑2:
我从代码中删除了未定义的行为。谢谢@sehe的通知。
没有循环,递归,条件和所有标准C…(qsort滥用):
#include <stdio.h>
#include <stdlib.h>
int numbers[51] = {0};
int comp(const void * a, const void * b){
numbers[0]++;
printf("%i\n", numbers[0]);
return 0;
}
int main()
{
qsort(numbers+1,50,sizeof(int),comp);
comp(NULL, NULL);
return 0;
}
我错过了所有的乐趣,所有好的c++答案都已经贴出来了!
这是我能想到的最奇怪的事情,我不认为它是合法的C99:p
#include <stdio.h>
int i = 1;
int main(int argc, char *argv[printf("%d\n", i++)])
{
return (i <= 1000) && main(argc, argv);
}
另一个,有点欺骗:
#include <stdio.h>
#include <boost/preprocessor.hpp>
#define ECHO_COUNT(z, n, unused) n+1
#define FORMAT_STRING(z, n, unused) "%d\n"
int main()
{
printf(BOOST_PP_REPEAT(1000, FORMAT_STRING, ~), BOOST_PP_ENUM(LOOP_CNT, ECHO_COUNT, ~));
}
最后一个想法,同样的欺骗:
#include <boost/preprocessor.hpp>
#include <iostream>
int main()
{
#define ECHO_COUNT(z, n, unused) BOOST_PP_STRINGIZE(BOOST_PP_INC(n))"\n"
std::cout << BOOST_PP_REPEAT(1000, ECHO_COUNT, ~) << std::endl;
}