題目:求1+2+…+n,
要求不能使用乘除法、for、while、if、else、switch、case等關鍵字以及條件判斷語句(A?B:C)。
/*
Name:
Copyright:
Author:
Date: 30-08-11 20:12
Description:
*/
#include<iostream>
#include<iomanip>
using namespace std;
int nPlus(int n)
{
int tem=0;
n&&(tem=nPlus(n-1));//&& 的短路性質相當於 if else 組合
return n+tem;
}
int main()
{
cout<<nPlus(100)<<endl;
system("pause");
return 0;
}
函數 nPlus也可以這樣寫:
int nPlus(int n)
{
int ret=0;
n&&(ret=n+nPlus(n-1));
return ret;
}
還有一種思路,利用構造函數:
#include<iostream>
#include<iomanip>
using namespace std;
class nPlus
{
public:
nPlus()
{
++N;
Sum+=N;
}
static int getSum()
{
return Sum;
}
static void reSet()
{
nPlus::N=Sum=0;
}
private:
static int N;
static int Sum;
};
int nPlus::N=0;
int nPlus::Sum=0;
int getResult(int n)
{
nPlus *t=new nPlus[n];
delete []t; return nPlus::getSum();
}
int main()
{
nPlus::reSet();
cout<<getResult(100)<<endl;
system("pause");
return 0;
}