#pragma once #include <iostream> using namespace std; template <typename T> double *wMA(T &tArray, int iWMALen) // 应用模版数据类型 typename T 引用外部数组 tArray { int iArrayLen = sizeof(tArray) / sizeof(tArray[0]); // 计算传入数组长度 = 总数组字节大小 / 首元素字节大小 cout << "Length of import array is: " << iArrayLen << endl; cout << "Import array is:"; for(int i = 0; i < iArrayLen; i++) { if(i == 0) cout << "[" << tArray[i] << " "; else if(i == iArrayLen - 1) cout << tArray[i] << "]" << endl; else cout << tArray[i] << " "; } if(iArrayLen >= iWMALen && iWMALen > 0) // 计算前提,数组长度不能小于均值要计算的天数 { int *pWMAW = new int[iWMALen]; // 把费波纳茨数列个值做权重 int iSumW = 0; // 费波纳茨数列的算术和 switch(iWMALen) { case 1: { cout << "Creating fabonacci numbers:" << endl; pWMAW[0] = 1; cout << "[0] = " << pWMAW[0] << endl; iSumW = pWMAW[0]; break; } case 2: { cout << "Creating fabonacci numbers:" << endl; pWMAW[0] = 1; pWMAW[1] = 1; cout << "[0] = " << pWMAW[0] << endl; cout << "[1] = " << pWMAW[1] << endl; iSumW = pWMAW[0] + pWMAW[1]; break; } default: { cout << "Creating fabonacci numbers:" << endl; pWMAW[0] = 1; pWMAW[1] = 1; cout << "[0] = " << pWMAW[0] << endl; cout << "[1] = " << pWMAW[1] << endl; iSumW = pWMAW[0] + pWMAW[1]; for(int i = 2; i < iWMALen; i++) { pWMAW[i] = pWMAW[i - 1] + pWMAW[i - 2]; // 费波纳茨通项公式算法 cout << "[" << i << "] = " << pWMAW[i] << endl; iSumW += pWMAW[i]; } break; } } cout << "The sum of those fabonacci numbers is: " << iSumW << endl; int n = iWMALen; // 固定均值计算天数,因为后面这个 iWMALen 会逐步增加变动 double *pWMAV = new double[iArrayLen]; // 用于保存均值 cout << "The wMA values are:" << endl; while(iWMALen <= iArrayLen) { double iSumV = 0; for(int i = iWMALen - n, j = 0; i < iWMALen; i++, j++) { iSumV += tArray[i] * pWMAW[j]; } pWMAV[iWMALen - 1] = iSumV / iSumW; // 算法 wMA = (数组个值 * 费波纳茨数列个值权重)的前 n 项和 / 费波纳茨数列加和 cout << "wMA[" << iWMALen - 1 << "] = " << pWMAV[iWMALen - 1] << endl; iWMALen++; } delete(pWMAW); // 该指针作用到此为止,释放指针 cout << "Remeber to delete the return pointer of wMA(...)!\n" << endl; // 函数返回指针,提示后面删除堆中新建指针 return pWMAV; } else { cout << "Error!\n" << endl; return NULL; } } int main() { int array[] = {1, 2, 5, 3, 4, 6, 18, 7}; double *p = wMA(array, 5); delete(p); cin.get(); return 0; }
时间: 2024-10-17 16:51:52