任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <stdio.h>
int show(int i) {
printf("%d\n",i);
return( (i>=1000) || show(i+1));
}
int main(int argc,char **argv) {
return show(1);
}
||操作符使递归调用短路,以显示i为>= 1000时的情况。
其他回答
适合c++爱好者
int main() {
std::stringstream iss;
iss << std::bitset<32>(0x12345678);
std::copy(std::istream_iterator< std::bitset<4> >(iss),
std::istream_iterator< std::bitset<4> >(),
std::ostream_iterator< std::bitset<4> >(std::cout, "\n"));
}
很难看透所有已经提出的解决方案,所以这可能是一个重复。
我想要一些相对简单的东西,只有纯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 <iostream>
template<int L, int U>
struct range
{
enum {H = (L + U) / 2};
static inline void f ()
{
range<L, H>::f ();
range<H+1, U>::f ();
}
};
template<int L>
struct range<L, L>
{
static inline void f ()
{
std::cout << L << '\n';
}
};
int main (int argc, char* argv[])
{
range<1, 1000>::f ();
return 0;
}
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }
这就像另一个以“愤怒”结尾的英语单词谜语,对吧?
未经测试,但应该是香草标准C:
void yesprint(int i);
void noprint(int i);
typedef void(*fnPtr)(int);
fnPtr dispatch[] = { noprint, yesprint };
void yesprint(int i) {
printf("%d\n", i);
dispatch[i < 1000](i + 1);
}
void noprint(int i) { /* do nothing. */ }
int main() {
yesprint(1);
}