Use c++ template It's very basic Help me

Asked 1 weeks ago, Updated 1 weeks ago, 0 views

#include<iostream>
#include <list>
using namespace std;

template<typename T>

T getSum(T list[], int n) {
    T sum = 0;  
    for (int i = 0; i < n; i++)     
        sum += list[i]; 
    return sum;
    }
int main() {
    cout << getSum ([1.2, 3.4, 2.5, 6.2], 10) << "\n"; // Error occurs here
    cout << sum;
    return 0;
}

I wrote it wrong, but I don't know how to fix it(Crying)

c++

2022-09-20 14:23

1 Answers

Please refer to the code below.

#include <iostream>
using namespace std;

template<typename T>
T getSum(T list[], int n) {
    T sum = 0;
    for (int i = 0; i < n; i++)
        sum += list[i];
    return sum;
}

int main()
{
    double x[] = { 1.2, 3.4, 2.5, 6.2 };
    double sum = getSum(x, sizeof(x) / sizeof(x[0]));
    cout << sum << '\n';
}


2022-09-20 14:23

If you have any answers or tips


© 2022 pinfo. All rights reserved.