An example that Uses static_cast promotion technique to avoid truncating

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. 

1 //function FindHypo use the area of the rectangle to determine the height and uses the result to calculate the hypotenuse of the triangle
2 #include <iostream>
3 #include <math.h>
4 double FindHypo (int RW, int Area, int TB)
5 {
6
7 int RecWidth =RW;
8 int RecArea=Area;
9 //double Height=RecArea/RecWidth; //if we use this expression the result will be trancated
10 double Height=static_cast<double>(RecArea)/RecWidth; //we use the static_cast to avoid trancation
11 int Tbase=TB;
12 double ThypoSqr =Height*Height+Tbase*Tbase;
13 double Thypo=sqrt(ThypoSqr);
14
15 return Thypo; // retun this data to the caller
16 } //end function FindHypo
17 //begin main
18 int main()
19 {
20 int Area=34;
21 int RecWidth=5;
22 int TriBase=5;
23 double TriHyp = FindHypo (RecWidth, Area, TriBase); //call to function FindHypo
24
25 // function main prints the result returned by function FindHypo
26 cout<<"The hypotenuse of the triangle is <TriHyp >>endl;
27
28 return 0;
29 }//end main
Output: The hypotenuse of the triangle is 8.44038
Back to introduction to functions

No comments:

Post a Comment