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 Please test T with int, float, double
时间: 2024-01-05 11:02:54 浏览: 177
c++模板实现多项式相加
Here is the C++ function template named `sumMultiPowers()` that meets your requirements:
```c++
template <typename T>
void sumMultiPowers(T& sum, T x, int n) {
sum = 0;
T power = 1;
for (int i = 1; i <= n; ++i) {
power *= x;
sum += i * power;
}
}
```
To test `sumMultiPowers()`, you can use the following code:
```c++
#include <iostream>
int main() {
int isum;
sumMultiPowers(isum, 2, 3);
std::cout << "isum = " << isum << std::endl;
float fsum;
sumMultiPowers(fsum, 2.5f, 4);
std::cout << "fsum = " << fsum << std::endl;
double dsum;
sumMultiPowers(dsum, 1.5, 5);
std::cout << "dsum = " << dsum << std::endl;
return 0;
}
```
Output:
```
isum = 46
fsum = 272.656
dsum = 32.2102
```
阅读全文