任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
OpenMP版本(当然是非有序的):
#include <iostream>
#include <omp.h>
int main(int argc, char** argv)
{
#pragma omp parallel num_threads(1000)
{
#pragma omp critical
{
std::cout << omp_get_thread_num() << std::endl;
}
}
return 0;
}
(不工作与VS2010 OpenMP运行时(限制为64线程),但工作在linux上,例如,英特尔编译器)
下面是一个有序的版本:
#include <stdio.h>
#include <omp.h>
int main(int argc, char *argv[])
{
int i = 1;
#pragma omp parallel num_threads(1000)
#pragma omp critical
printf("%d ", i++);
return 0;
}
其他回答
没人说它不应该事后分段错误,对吧?
注意:这在我的64位Mac OS X系统上正常工作。对于其他系统,您需要将参数更改为setrlimit,并相应地更改spacecew的大小。: -)
(我不应该包括这个,但以防万一:这显然不是一个好的编程实践的例子。然而,它确实有一个优点,那就是它利用了这个网站的名称。)
#include <sys/resource.h>
#include <stdio.h>
void recurse(int n)
{
printf("%d\n", n);
recurse(n + 1);
}
int main()
{
struct rlimit rlp;
char spacechew[4200];
getrlimit(RLIMIT_STACK, &rlp);
rlp.rlim_cur = rlp.rlim_max = 40960;
setrlimit(RLIMIT_STACK, &rlp);
recurse(1);
return 0; /* optimistically */
}
使用指针算术,我们可以将数组自动初始化为0。
#include <stdio.h>
void func();
typedef void (*fpa)();
fpa fparray[1002] = { 0 };
int x = 1;
void func() {
printf("%i\n", x++);
((long)fparray[x] + &func)();
}
void end() { return; }
int main() {
fparray[1001] = (fpa)(&end - &func);
func();
return 0;
}
易如反掌!: P
#include <iostream>
static int current = 1;
struct print
{
print() { std::cout << current++ << std::endl; }
};
int main()
{
print numbers [1000];
}
这是我的两个解。第一个是c#,第二个是C语言:
C#:
const int limit = 1000;
Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n); actions[Math.Sign(limit - n-1)](n + 1); };
actions[1](0);
C:
#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))
void (*actions[3])(int);
void Action0(int n)
{
printf("%d", n);
}
void Action1(int n)
{
int index;
printf("%d\n", n);
index = sign(998-n)+1;
actions[index](++n);
}
void main()
{
actions[0] = &Action0;
actions[1] = 0; //Not used
actions[2] = &Action1;
actions[2](0);
}
令人惊讶的是,如果你放弃了“必须是C或c++”的要求,事情会变得多么简单:
Unix shell:
echo {1..1000} | tr ' ' '\n'
or
yes | nl | awk '{print $1}' | head -1000
如果你在一个没有yes命令的Unix变体上运行,使用其他进程至少生成1000行:
find / 2> /dev/null | nl | awk '{print $1}' | head -1000
or
cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000
or
head -1000 /etc/termcap | nl -s: | cut -d: -f1