任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Printer
{
public:
Printer() { cout << ++i_ << "\n"; }
private:
static unsigned i_;
};
unsigned Printer::i_ = 0;
int main()
{
Printer p[1000];
}
其他回答
简单C版本,在1000处终止:
int print_stuff(int count) {
printf("%d\n", count);
return (count ^ 1000) && print_stuff(count+1);
}
int main(int argc, char *argv[]) {
print_stuff(1);
return 0;
}
很难看透所有已经提出的解决方案,所以这可能是一个重复。
我想要一些相对简单的东西,只有纯C,而不是c++。它使用递归,但与我看到的其他解相反,它只做对数深度的递归。通过查找表可以避免使用条件。
typedef void (*func)(unsigned, unsigned);
void printLeaf(unsigned, unsigned);
void printRecurse(unsigned, unsigned);
func call[2] = { printRecurse, printLeaf };
/* All array members that are not initialized
explicitly are implicitly initialized to 0
according to the standard. */
unsigned strat[1000] = { 0, 1 };
void printLeaf(unsigned start, unsigned len) {
printf("%u\n", start);
}
void printRecurse(unsigned start, unsigned len) {
unsigned half0 = len / 2;
unsigned half1 = len - half0;
call[strat[half0]](start, half0);
call[strat[half1]](start + half0, half1);
}
int main (int argc, char* argv[]) {
printRecurse(0, 1000);
}
这甚至可以通过使用一个指针动态地完成。相关的变化:
unsigned* strat = 0;
int main (int argc, char* argv[]) {
strat = calloc(N, sizeof(*strat));
strat[1] = 1;
printRecurse(0, N);
}
#include <stdio.h>
typedef void (*fp) (int);
void stop(int i)
{
printf("\n");
}
void next(int i);
fp options[2] = { next, stop };
void next(int i)
{
printf("%d ", i);
options[i/1000](++i);
}
int main(void)
{
next(1);
return 0;
}
template <int To, int From = 1>
struct printer {
static void print() {
cout << From << endl;
printer<To, From + 1>::print();
}
};
template <int Done>
struct printer<Done, Done> {
static void print() {
cout << Done << endl;
}
};
int main()
{
printer<1000>::print();
}
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;
}