题目:求1 + 2 + 3 + ... + n 的和
要求:不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
答:
#include "stdafx.h"#includeusing namespace std;//1、函数查找表法typedef int (*Func)(int n);int Sum1(int n){ return 0;}int Sum2(int n){ Func sum[2] = {Sum1, Sum2}; return sum[n > 0](n - 1) + n;}//2、&&短路特性int CountSum(int n, int &total){ n && CountSum(n - 1, total); return total += n;}//3、构造函数法class SumClass{public: SumClass() { n++; sum += n; } static int GetSum() { return sum; }private: static int n; static int sum;};int SumClass::n = 0;int SumClass::sum = 0;int _tmain(int argc, _TCHAR* argv[]){ cout<<"1、函数查找表:1+2+3+...+100 = "< <
运行界面如下: