作者:mobiledu2502914875 | 来源:互联网 | 2024-12-25 14:31
### 方法一:使用循环结构
#include
int sumUsingLoop(int n)
{
int total = 0;
while (n > 0)
{
total += n;
n--;
}
return total;
}
int main()
{
printf("Sum: %d\n", sumUsingLoop(10));
return 0;
}
### 方法二:利用递归函数
int sumUsingRecursion(int n)
{
if (n == 1)
return 1;
else
return n + sumUsingRecursion(n - 1);
}
int main()
{
printf("Sum: %d\n", sumUsingRecursion(10));
return 0;
}
### 方法三:基于类的构造函数
#include
using namespace std;
class SumCalculator
{
public:
SumCalculator() { currentNumber++; totalSum += currentNumber; }
static int getTotalSum() { return totalSum; }
private:
static int currentNumber;
static int totalSum;
};
int SumCalculator::currentNumber = 0;
int SumCalculator::totalSum = 0;
int main()
{
SumCalculator* calculators = new SumCalculator[10];
cout <<"Sum: " < delete[] calculators;
return 0;
}
### 方法四:模板元编程(TMP)
#include
using namespace std;
template<int N>
int sumUsingTemplate()
{
return N + sumUsingTemplate1>();
}
template<>
int sumUsingTemplate<1>()
{
return 1;
}
int main()
{
cout <<"Sum: " <10>() < return 0;
}