Create the C++ Function Template named sumMultiPowers() so that it has three parameters sum, x, and n. The first two parameters will have the type represented by the function template type parameter T. n will always be int. The return type is void. All parameters are passed by value except for sum which is passed by reference. A Template Function created from sumMultiPowers() will compute sum = 1 + x + 2x^2 + 3x^3 + ... + nx^n
时间: 2024-01-05 17:02:54 浏览: 93
Here's the C++ function template named sumMultiPowers() that meets the requirements you specified:
```c++
template <typename T>
void sumMultiPowers(T& sum, T x, int n) {
sum = 0;
T term = 1;
for (int i = 0; i <= n; i++) {
sum += term;
term *= x;
term *= i + 1;
term /= i;
}
}
```
Explanation:
- The function template has one type parameter T, which represents the type of sum and x.
- The first parameter sum is passed by reference using the `&` symbol, so that changes made to it inside the function are reflected outside the function.
- The second parameter x is passed by value, because it does not need to be modified inside the function.
- The third parameter n is an int, because it represents the number of terms to be added.
- The function template computes the sum using a loop that goes from 0 to n.
- Inside the loop, it computes the current term using `term *= x`, and then multiplies it by `(i+1)/i` to get the next term.
- Finally, it adds the current term to the sum using `sum += term`.
阅读全文