There are times when the parameter types of a function are not able to produced desired results if used as declared. Consider the diagram below. As you can see both the rectangle and the triangle share the same height, H. Given the area of a rectangle, we can determine its height which we then use to calculate the hypotenuse (Hp) of the triangle with a help of the Pythagoras theorem.
Let us assume Area=34 and is of type int as is width W. A function to calculate the height of the rectangle using H= Area/W can produce a wrong result because the answer would be truncated given that both Area and W are of type int. The solution is to use the promotion rules so as to avoid truncation.
Anyway, let us first go manual so as to be sure of the results of this problem;
Now that we know the right results let us see if the program below with a function that uses the above calculations would produce the same result. We use the static_cast(valueToPromote) to promote type int to a double to avoid truncation of Area/W.
|
|
Back to introduction to functions |
No comments:
Post a Comment