编程算法 - 求1+2+...+n(模板类) 代码(C++)
求1+2+...+n(模板类) 代码(C++)
本文地址: http://blog.csdn.net/caroline_wendy
题目: 求1+2+...+n, 要求不能使用乘除法\for\while\if\else\switch\case等keyword及条件推断语句(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\n", result);
return 0;
}
输出:
result = 55
posted on 2017-06-05 14:04 cynchanpin 阅读(399) 评论(0) 收藏 举报
浙公网安备 33010602011771号