任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
与宏!
#include<stdio.h>
#define x001(a) a
#define x002(a) x001(a);x001(a)
#define x004(a) x002(a);x002(a)
#define x008(a) x004(a);x004(a)
#define x010(a) x008(a);x008(a)
#define x020(a) x010(a);x010(a)
#define x040(a) x020(a);x020(a)
#define x080(a) x040(a);x040(a)
#define x100(a) x080(a);x080(a)
#define x200(a) x100(a);x100(a)
#define x3e8(a) x200(a);x100(a);x080(a);x040(a);x020(a);x008(a)
int main(int argc, char **argv)
{
int i = 0;
x3e8(printf("%d\n", ++i));
return 0;
}
其他回答
我认为这些代码工作完全正确,很容易理解,你可以打印任何像1到100或1到最终范围。把它放在I中,然后转移到call function中。
int main()
{
int i=1;
call(i,i);
}
void call(int i,int j)
{
printf("%d",i);
sleep(1); // to see the numbers for delay
j /= (j-1000);
j = ++i;
call(i,j);
}
所以当j等于1000时,它会被除零,然后直接退出程序这就是我打印数字的想法
或者更简单的代码..
int main()
{
static int i = 1;
static int j = 1;
printf("%d", i);
sleep(1);
j = ++i;
j /= (j-1000);
main();
}
除了基本的字符串处理,你真的不需要任何东西:
#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";
}
编译时递归!: P
#include <iostream>
template<int N>
struct NumberGeneration{
static void out(std::ostream& os)
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
};
template<>
struct NumberGeneration<1>{
static void out(std::ostream& os)
{
os << 1 << std::endl;
}
};
int main(){
NumberGeneration<1000>::out(std::cout);
}
也可以通过简单的动态调度来实现(在Java中也适用):
#include<iostream>
using namespace std;
class U {
public:
virtual U* a(U* x) = 0;
virtual void p(int i) = 0;
static U* t(U* x) { return x->a(x->a(x->a(x))); }
};
class S : public U {
public:
U* h;
S(U* h) : h(h) {}
virtual U* a(U* x) { return new S(new S(new S(h->a(x)))); }
virtual void p(int i) { cout << i << endl; h->p(i+1); }
};
class Z : public U {
public:
virtual U* a(U* x) { return x; }
virtual void p(int i) {}
};
int main(int argc, char** argv) {
U::t(U::t(U::t(new S(new Z()))))->p(1);
}
触发致命错误!这是文件,counup .c:
#include <stdio.h>
#define MAX 1000
int boom;
int foo(n) {
boom = 1 / (MAX-n+1);
printf("%d\n", n);
foo(n+1);
}
int main() {
foo(1);
}
编译,然后在shell提示符下执行:
$ ./countup
1
2
3
...
996
997
998
999
1000
Floating point exception
$
这确实打印了从1到1000的数字,没有任何循环或条件!