Pass function pointer

#include <iostream>

using namespace std;

double squared(double);
double cubed(double);
double sumArray(const double arr[], size_t len, double (*pFunc)(double));

int main()
{
    double arr[]{ 1.5,2.5,3.5,4.5,5.5,6.5,7.5 };
    size_t len{ _countof(arr) };

    cout << "Sum of squares=" << sumArray(arr, len, squared) << endl;
    cout << "Sum of cubes=" << sumArray(arr, len, cubed) << endl;
}

double sumArray(const double arr[], size_t len, double (*pFunc)(double))
{
    double total{};
    for (size_t i{};i < len;i++)
    {
        total += pFunc(arr[i]);
    }
    return total;
}

double cubed(double x)
{
    return x * x * x;
}

double squared(double x)
{
    return x * x;
}

 

posted @ 2022-09-07 23:32  FredGrit  阅读(14)  评论(0编辑  收藏  举报