sumcount2.cpp

来自「这是数据结构、算法与应用-C++语言描述的代码」· C++ 代码 · 共 40 行

CPP
40
字号
// simplified step count of sum of n numbers

#include <iostream>
#include <algorithm> // has copy

using namespace std;


int stepCount = 0;

template<class T>
T sum(T a[], int n)
{// Return sum of numbers a[0:n - 1].
   for (int i = 0; i < n; i++)
      stepCount += 2;
   stepCount += 3; 
   return 0;
}

int main()
{
   int a[6] = {1, 2, 3, 4, 5, 6};

   // output the array elements
   cout << "a[0:5] = ";
   copy(a, a+6, ostream_iterator<int>(cout, " "));
   cout << endl;

   // determine the step count
   sum(a,0);
   cout << "For sum(a,0) the step count is " << stepCount << endl;
   stepCount = 0;
   sum(a,1);
   cout << "For sum(a,1) the step count is " << stepCount << endl;
   stepCount = 0;
   sum(a,6);
   cout << "For sum(a,6) the step count is " << stepCount << endl;
   return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?