任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
这是我的两个解。第一个是c#,第二个是C语言:
C#:
const int limit = 1000;
Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n); actions[Math.Sign(limit - n-1)](n + 1); };
actions[1](0);
C:
#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))
void (*actions[3])(int);
void Action0(int n)
{
printf("%d", n);
}
void Action1(int n)
{
int index;
printf("%d\n", n);
index = sign(998-n)+1;
actions[index](++n);
}
void main()
{
actions[0] = &Action0;
actions[1] = 0; //Not used
actions[2] = &Action1;
actions[2](0);
}
其他回答
不懂足够的C(++)来写代码,但你可以使用递归而不是循环。为了避免这种情况,可以使用在第1000次访问后抛出异常的数据结构。例如,某种带有范围检查的列表,在每次递归时增加/减少索引。
从评论中判断,c++中似乎没有任何范围检查列表?
相反,你可以用1/n作为递归函数的参数,每次调用都减少1。从1000开始。DivisionByZero异常将停止递归
除了基本的字符串处理,你真的不需要任何东西:
#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>
void main(int i){printf("%d\n",i)&&i++<1000&&(*((int*)&i-1)-=5);}
另一个:
#include <stdio.h>
int main(int i){return i<=1000&&printf("%d\n",i)&&main(++i);}
我认为这些代码工作完全正确,很容易理解,你可以打印任何像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();
}
函数指针(ab)使用。没有预处理器的魔力来增加输出。ANSI C。
#include <stdio.h>
int i=1;
void x10( void (*f)() ){
f(); f(); f(); f(); f();
f(); f(); f(); f(); f();
}
void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }
int main(){
M();
}