求1+2+3+···+n,要求不用for、while、if、else、switch、case等控制语句
这道题本身并不难,主要难在限制条件。通常情况我们求n的前n项和除了用前n项和公式n*(n+1)/2外,就是用循环和递归,连续累加n次。但是题目要求不用循环控制语句。这给我们出了一个难题。如果用循环就要用到while或者for,用递归的话就要用到if判断。这该怎么办呢?
解法一:
求n个数的累加和就是让累加n次。我们可以在一个类中定义静态变量,然后用构造函数来操作这个变量,然后输出结果。那怎么能让构造函数不用循环和递归操作n次呢,我们于是想到定义数组,这样就会连续调用n次构造函数,以实现我们的目的
class A
{
public:
A()
{
sum+=n;
n++;
}
static int sum;
static int n;
};
int A::n=1;
int A::sum=0;
A a[5]=new A[5];
cout<<A::sum<<endl;
delete []a;
这样的话就可以求出结果
解法二:
我们还可以用虚函数来解决这个问题,定义一个类和类中的虚函数,让另一个类去继承
class B
{
public:
virtual int sum(int n)
{
return 0;
}
};
B *array[2];
class C:public B
{
public:
int sum(int n)
{
return n+array[!!(n-1)]->sum(n-1); //对一个数!之后就变成0,再一次取反就变成1
}
};
B b;
C c;
array[0]=&b;
array[1]=&c;
cout<<c.sum(5)<<endl;
解法三:
把上边的思路拓展一下,我们可以想到用函数指针,也是定义一个数组
int (*ptr[2])(int); //定义一个函数指针数组
int fun1(int n)
{
return 0;
}
int fun2(int n)
{
return n+ptr[!!(n-1)](n-1);
}
//下面这几句在主函数中
ptr[0]=fun1;
ptr[1]=fun2;
cout<<fun2(5)<<endl;
解法四:
用函数模板,以及模板特化
template <int n>
struct D
{
enum sum {N=D<n-1>::N+n};
};
template <>
struct D<1>
{
enum sum{N=1};
};
cout<<D<5>::N<<endl;