A.9. Chapter 11
A.9.1. Exercise 1 Solution
The error message is:
Use of unassigned local variable 'x'
The problem is that C# doesn't want you to return a variable that has not been explicitly assigned a value. In the code, x is assigned a value only when the if statement is true. To fix the problem, you must explicitly assign x a value. The easiest fix is to change the definition of x:
int x = 0;
A.9.2. Exercise 2 Solution
The issue here is not whether you can code the equation correctly, but whether you can make it readable for others. The first solution might be
p = a * 1 / (Math.Pow(1 + i, y));
The code would compile and generate the correct values for p. However, which would you rather debug: the preceding statement or the following?
presentValue = futureAmount * 1.0 / (Math.Pow(1.0 + interestRate, yearsIntoFuture));
The primary difference is the use of meaningful variable names. Another benefit is the use of numeric constants (1.0) that reflect the fact that floating-point values are being used in the equation. You could make the argument that the decimal data type should be used since this is a financial calculation. However, the pow() method uses the double data type, so I would probably stuff this equation into a method that returned a double and let the user decide to cast it to a decimal if needed.
An alternative that makes debugging a bit easier would be:
discountFactor = 1.0 / (Math.Pow(1.0 + interestRate, yearsIntoFuture)); presentValue = futureAmount * discountFactor; ...
Get Beginning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.