任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include "stdafx.h"
static n=1;
class number {
public:
number () {
std::cout << n++ << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
number X[1000];
return 0;
}
其他回答
printf("%d\n", 2);
printf("%d\n", 3);
它不会打印所有的数字,但它会“打印从1到1000的数字”。暧昧的问题求赢!:)
很难看透所有已经提出的解决方案,所以这可能是一个重复。
我想要一些相对简单的东西,只有纯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);
}
经过一些修改,我想出了这个:
template<int n>
class Printer
{
public:
Printer()
{
std::cout << (n + 1) << std::endl;
mNextPrinter.reset(new NextPrinter);
}
private:
typedef Printer<n + 1> NextPrinter;
std::auto_ptr<NextPrinter> mNextPrinter;
};
template<>
class Printer<1000>
{
};
int main()
{
Printer<0> p;
return 0;
}
后来@ybungalobill的作品启发我想出了这个更简单的版本:
struct NumberPrinter
{
NumberPrinter()
{
static int fNumber = 1;
std::cout << fNumber++ << std::endl;
}
};
int main()
{
NumberPrinter n[1000];
return 0;
}
#include <stdio.h>
void main(int i){printf("%d\n",i)&&i++<1000&&(*((int*)&i-1)-=5);}
另一个:
#include <stdio.h>
int main(int i){return i<=1000&&printf("%d\n",i)&&main(++i);}
只需使用std::copy()和一个特殊的迭代器。
#include <algorithm>
#include <iostream>
#include <iterator>
struct number_iterator
{
typedef std::input_iterator_tag iterator_category;
typedef int value_type;
typedef std::size_t difference_type;
typedef int* pointer;
typedef int& reference;
number_iterator(int v): value(v) {}
bool operator != (number_iterator const& rhs) { return value != rhs.value;}
number_iterator operator++() { ++value; return *this;}
int operator*() { return value; }
int value;
};
int main()
{
std::copy(number_iterator(1),
number_iterator(1001),
std::ostream_iterator<int>(std::cout, " "));
}