2: Calculate the multiplication of a number. Of course, this can be done by using the pow function in the cmath header file. However, this method is less efficient for the multiplication of long integers with a small number of times. It is better to manually write an operand concatenation expression, but sometimes this is not convenient, especially when the base number of the multiplication operator itself is a more complex expression
2: Calculate the multiplication of a number. Of course, this can be done by using the pow function in the cmath header file. However, this method is less efficient for the multiplication of long integers with a small number of times. It is better to manually write an operand concatenation expression, but sometimes this is not convenient, especially when the base number of the multiplication operator itself is a more complex expression
2: Calculate the multiplication of a number.
Of course, this can be done by using the pow function in the cmath header file. However, this method is less efficient for the multiplication of long integers with a small number of times. It is better to manually write an operand concatenation expression, but sometimes this is not convenient. Especially when the base number of the multiplication operator is itself a complicated expression, it is usually necessary to save the expression with a temporary variable and then multiply the temporary variable. Defining the following inline function provides some convenience.
Inline double power (double x, unsigned n)
{
Double result = x;
For (int I = 1; I <n; I ++)
Result * = x;
Return result;
}
When n is relatively small, the efficiency of this function is usually higher than that of the pow function in the cmath header file. However, this function must execute a loop during runtime and does not achieve the ideal efficiency, the template element came in handy again. As follows:
Template
Inline double power (double v)
{
Return v * power (V );
}
Template <>
Inline double power <1> (double v)
{
Return v;
}
The template above is not general enough and can only be of the double type. The new type parameter T is referenced below. Because the function template does not support the special feature, we cannot directly specify the result when N = 1, so we can use a class template.
Template
Struct Power
{
Template
Static T value (T x)
{
Return x * Power : Value (x );
};
Template <>
Struct Power <1>
{
Template
Static T value
{
Reurn x;
}
In this way, we can calculate the 4 Power of x and write: Power <4 >:: value (x );
However, this is inconvenient to write, so we can write an auxiliary template function, as shown below:
Template
{
Inline T Power (T v)
Return Power : Value (v );
}
In this way, the power of x can be written as follows: power <4> (x );
}