Area of Triangle using base and height
Finding the area of a triangle when base and height is given
Learning Objectives
- Learning to build simple expressions.
- Taking extra care of numerator data type when divisions are performed.
- Learning alternate ways of writing expressions.
Program Approach
- Will collect base and height values.
- Will write the formula suitable for c++ style of calculations using the correct data types.
- Will output the results.
Source Code
|
|
Run Output
Code Understanding
float a,b,h;
cout<<“Enter base and height of triangle:”;
cin>>b>>h;
These are lines for simple user input with two variables entered one after the another with a space, tab or enter in between.
a=b*h/2;
We can not use the most common form 1/2*b*h here as dividing 1 with 2 will produce 0 being an integer division. Means fraction portion will be removed. with b*h/2 form of expression, since both b and h are of float type, float division will occur and division by 2 will retain the fractional part also, which can then be stored in variable a which is also a float variable. The alternate form for this statement can be a=0.5*b*h; This form works well even if b and h are integer type of variables. The variable a must definitely be a float or double type variable as it is most likely be a fractional value.
Notes
- The data types will always have specific storage space, so the test values shall be given accordingly.
- Some authors prefer to give double type/long double for all fraction numbers owing to larger computing space available these days. We recommend the use of correct data type as per application need for optimized performance.
Suggested Filename(s): areaoftriangle.cpp, areatri.cpp
Created: 19-Dec-2017 01:55 | Updated: 20-Jan-2018 17:21|
