Welcome

首页 / 软件开发 / 数据结构与算法 / 编程算法:求1+2+...+n(模板类) 代码(C++)

编程算法:求1+2+...+n(模板类) 代码(C++)2015-10-20题目: 求1+2+...+n, 要求不能使用乘除法forwhileifelseswitchcase等关键字及条件判断语句(A?B:C).

可以使用模板类求解, 输入模板参数, 进行递归调用, 每次递归值减1, 至模板参数为1时, 显示调用结束模板类.

代码:

/** main.cpp**Created on: 2014.7.12* *Author: spike*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>template <size_t n> struct Sum {enum Value { N = Sum<n-1>::N + n};};template <> struct Sum<1> {enum Value {N=1};};int main(void){size_t result = Sum<10>::N;printf("result = %d
", result);return 0;}
输出:

result = 55
作者:csdn博客 Caroline-Wendy