Write a C++ program that contain 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 11:02:54 浏览: 199
Here's a C++ program that contains the `sumMultiPowers()` function template you specified:
```c++
#include <iostream>
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;
}
}
int main() {
double sum_double, x_double;
int n_int;
std::cout << "Enter a value for x: ";
std::cin >> x_double;
std::cout << "Enter a value for n: ";
std::cin >> n_int;
sumMultiPowers(sum_double, x_double, n_int);
std::cout << "The sum is: " << sum_double << std::endl;
return 0;
}
```
Explanation:
- The program first declares the variables `sum_double`, `x_double`, and `n_int`, which will be used to store the sum, the value of x, and the number of terms to be added, respectively.
- It then prompts the user to enter a value for `x` and `n`.
- Next, it calls the `sumMultiPowers()` function template with the appropriate arguments.
- Finally, it outputs the value of `sum` using `std::cout`.
阅读全文