Two issues add to the complexity of the solution: The first is the exponent in the numerator, and the second is the two minus operators, one each in the numerator and the denominator.
We can simplify the exponent: -(n-x) = -n+x = x-n. However, I leave it as it appears in the original problem to serve as an example of the minimal use of parentheses when converting formulas to C++ code. The exponentiation operation (i.e., raising a number to a power) has a high precedence, which means that we can focus our attention on just part of the numerator for now:
\[ (x+1)(1+i)^{-(n-x)} \]We can use the pow function to raise a number to a power. The function requires a base and an exponent: be = pow(b,e)
. The most challenging aspect of converting the numerator to C++ code is understanding which part is the base and which part is the exponent. The numerator has three main parts that are easier to see if we make three simple substitutions:
a = x + 1;
b = 1 + i;
c = n - x;
Now the numerator becomes: 1 - ab-c
. Exponentiation has a higher precedence than multiplication and takes place first: a(bc)
, which is a * pow(b, -c)
in C++ code. Notice that the only parentheses needed are those that form the argument list for the pow function. Although we can program the final solution based on the three substitutions made above, the variables a, b, and c have no real meaning in the context of the problem: the substitutions were just a way of helping us see what to do with the exponent. The full C++ implementation of the numerator is:
1 - (x + 1) * pow(1 + i, -(n - x))
Finally, notice that the comma separating the base and exponent is sufficient to separate the two expressions - additional grouping parentheses are unnecessary. The parentheses in -(n-x)
are needed for the unary negation operator, but we can remove them as noted above. While the temporary variables might help us develop a solution, they can make the final C++ more difficult to understand (see Misusing temporary variables), so they should not be in the final solution.
The long horizontal line is the division operator, which has higher precedence than the two minus operators. When used this way, the division operator acts as a set of grouping parentheses - meaning the formula evaluates the numerator and the denominator before the division operation takes place: (numerator) / (denominator)
.
()
, brackets []
, and braces {}
for grouping. But C++ uses brackets and braces for tasks unrelated to grouping. You must replace brackets and braces in formulas with parentheses in C++.ab
is translated to C++ as a * b
R[. . .]
is translated to C++ as R * [. . .]
. In this problem, you must replace the brackets with parentheses