任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
static void Main(string[] args)
{
print(1000);
System.Console.ReadKey();
}
static bool print(int val)
{
try
{
print( ((val/val)*val) - 1);
System.Console.WriteLine(val.ToString());
}
catch (Exception ex)
{
return false;
}
return true;
}
其他回答
很难看透所有已经提出的解决方案,所以这可能是一个重复。
我想要一些相对简单的东西,只有纯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;
}
你可以使用递归。
是这样的:
void Print(int n)
{
cout<<n<<" ";
if(n>1000)
return
else
return Print(n+1)
}
int main ()
{
Print(1);
}
使用系统命令:
system("/usr/bin/seq 1000");
#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;
}