【正确答案】
【答案解析】一般而言,采用控制流程语句,如for、while等都可以很容易地执行打印工作。例如,
int i;
for(i=1;i<=1000;i++)
printf("%d/n",i);
但按照题目要求,不允许用流程控制语句,所以需要采取非常规的方法来完成打印工作。一般能想到的方法是采用构造函数以及宏定义两种不同的方式来实现。
方法一,采用构造函数与静态构造变量结合的方法实现。首先在类中定义一个静态成员变量,然后在构造函数里面打印该静态变量的值,并对静态变量进行自增操作,同时在主函数里面定义一个类数组,程序代码示例如下:
#include<stdio.h>
struct print
{
static int a;
print()
{
printf("%d/n",print::a);
a++;
}
};
int print::a=1;
int main()
{
print tt[1000];
return 0;
}
方法二,可以通过使用宏定义来实现。
#include<stdio.h>
#define B P,P,P,P,P,P,P,P,P,P
#define P L,L,L,L,L,L,L,L,L,L
#define L I,I,I,I,I,I,I,I,I,I,N
#define I printf("%3d",i++)
#define N printf("/n")
int main()
{
int i=1;
B;
return 0;
}
宏定义更简便的写法如下:
#include<stdio.h>
#define A(x) x;x;x;x;x;x;x;x;x;x;
int main()
{
int n=1;
A(A(A(printf("%d",n++))));
return 0;
}
与此题类似的题目还有:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。通常针对此类题目除了用公式n(n+1)/2之外,还可以用循环和递归两种思路,由于不能使用for和while,循环已经不能再用了。同样,一般的递归函数也需要用if语句或者条件判断语句来判断是继续递归下去还是终止递归,所以一般的递归函数也无法满足本题的需要。
根据本题的思路可以采用构造函数与静态变量结合的方式,程序示例如下:
#include<iostream>
using namespace std;
class Temp
{
public:
Temp();
static void Reset();
static int GetSum();
private:
static int N;
static int Sum;
int Temp::N =0;
int Temp::Sum =0;
Temp::Temp()
{
++N;
Sum+=N;
}
void Temp::Reset()
{
N=0;
Sum=0;
}
int Temp::GetSum()
{
return Sum;
}
int Sum(int n)
{
Temp::Reset();
Temp *a =new Temp[n];
delete []a;
a=0;
return Temp::GetSum();
int main()
{
printf("%d/n",Sum(10));
return 0;
}
程序的输出结果:
55
除了以上提及的方法以外,还有很多其他方法,虽然说一般的递归函数无法解决本题问题,但是如果能够不使用条件判断语句来进行递归条件的判断,则此种递归方法可取,于是设计出了如下方法:
#include<stdio.h>
int func(int n)
{
int i=1;
(n>1)&&(i=func(n-1)+n);
return i;
}
int main()
{
printif(%d/n",func(10));
return 0;
}
程序输出结果:
55
该方法非常巧妙,有兴趣的读者还可以在此基础上进行更多的发散思维。