任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
除了基本的字符串处理,你真的不需要任何东西:
#include <iostream>
#include <algorithm>
std::string r(std::string s, char a, char b)
{
std::replace(s.begin(), s.end(), a, b);
return s;
}
int main()
{
std::string s0 = " abc\n";
std::string s1 = r(s0,'c','0')+r(s0,'c','1')+r(s0,'c','2')+r(s0,'c','3')+r(s0,'c','4')+r(s0,'c','5')+r(s0,'c','6')+r(s0,'c','7')+r(s0,'c','8')+r(s0,'c','9');
std::string s2 = r(s1,'b','0')+r(s1,'b','1')+r(s1,'b','2')+r(s1,'b','3')+r(s1,'b','4')+r(s1,'b','5')+r(s1,'b','6')+r(s1,'b','7')+r(s1,'b','8')+r(s1,'b','9');
std::string s3 = r(s2,'a','0')+r(s2,'a','1')+r(s2,'a','2')+r(s2,'a','3')+r(s2,'a','4')+r(s2,'a','5')+r(s2,'a','6')+r(s2,'a','7')+r(s2,'a','8')+r(s2,'a','9');
std::cout << r(r(s1,'a',' '),'b',' ').substr(s0.size())
<< r(s2,'a',' ').substr(s0.size()*10)
<< s3.substr(s0.size()*100)
<< "1000\n";
}
其他回答
#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。
未经测试,但应该是香草标准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);
}
既不是循环语句也不是条件语句,至少它不会在我的机器上崩溃:)。使用一些指针魔法我们有。
#include <stdlib.h>
#include <stdio.h>
typedef void (*fp) (void *, int );
void end(fp* v, int i){
printf("1000\n");
return;
}
void print(fp *v, int i)
{
printf("%d\n", 1000-i);
v[i-1] = (fp)print;
v[0] = (fp)end;
(v[i-1])(v, i-1);
}
int main(int argc, char *argv[])
{
fp v[1000];
print(v, 1000);
return 0;
}
Manglesky的解决方案很棒,但还不够模糊。: -):
#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d\n", i++);))) return 0; }
#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];
}