题目:求1 + 2 + 3 + ... + n 的和
要求:不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
答:
#include "stdafx.h" #include <iostream> using 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 = "<<Sum2(100)<<endl; int total = 0; CountSum(100, total); cout<<"2、&&短路特性:1+2+3+...+100 = "<<total<<endl; SumClass *p = new SumClass[100]; delete []p; cout<<"3、构造函数法:1+2+3+...+100 = "<<SumClass::GetSum()<<endl; return 0; }
运行界面如下: