求1+2+3+....n

要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)

解法一:

n个数的累加和就是让累加n次。我们可以在一个类中定义静态变量,然后用构造函数来操作这个变量,然后输出结果。那怎么能让构造函数不用循环和递归操作n次呢,我们于是想到定义数组,这样就会连续调用n次构造函数,以实现我们的目的

#include<iostream>
using namespace std;
class Test
{
public:
   Test()
   {
    sum+=n;
    n++;  
   }
   static int sum;
   static int n;
};
int Test::n=1;
int Test::sum=0;
int main()
{
 Test* test=new Test[5];
 cout<<Test::sum<<endl;
 return 0;
}

解法二:

我们还可以用虚函数来解决这个问题,定义一个类和类中的虚函数,让另一个类去继承

#include<iostream>
using namespace std;

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  
  } 
};
int main()
{
 B b; 
 C c;  
 array[0]=&b;  
 array[1]=&c;  
 cout<<c.sum(5)<<endl; 
}

解法三:

把上边的思路拓展一下,我们可以想到用函数指针,也是定义一个数组

#include<iostream>
using namespace std;
int (*ptr[2])(int); //定义一个函数指针数组  
int fun1(int n) 

    return 0; 

int fun2(int n) 

    return n+ptr[!!(n-1)](n-1); 

//下面这几句在主函数中  
int main()
{
  ptr[0]=fun1; 
  ptr[1]=fun2; 
  cout<<fun2(5)<<endl; 
  return 0;
}
解法四:

用函数模板,以及模板特化

#include<iostream>
using namespace std;
template <int n> 
struct D 

    enum sum {N=D<n-1>::N+n}; 
}; 
template <> 
struct D<1> 

    enum sum{N=1}; 
}; 
int main()
{
  cout<<D<5>::N<<endl; 
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值