任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
使用宏压缩:
#include <stdio.h>
#define a printf("%d ",++i);
#define b a a a a a
#define c b b b b b
#define d c c c c c
#define e d d d d
int main ( void ) {
int i = 0;
e e
return 0;
}
或者更好:
#include <stdio.h>
#define a printf("%d ",++i);
#define r(x) x x x x x
#define b r(r(r(a a a a)))
int main ( void ) {
int i = 0;
b b
return 0;
}
其他回答
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:
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);
}
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();
}
#include <iostream>
#include <iterator>
using namespace std;
int num() { static int i = 1; return i++; }
int main() { generate_n(ostream_iterator<int>(cout, "\n"), 1000, num); }
#include <stdio.h>
int i = 0;
p() { printf("%d\n", ++i); }
a() { p();p();p();p();p(); }
b() { a();a();a();a();a(); }
c() { b();b();b();b();b(); }
main() { c();c();c();c();c();c();c();c(); return 0; }
我很惊讶似乎没有人张贴这个——我认为这是最明显的方式。1000 = 5*5*5*8。