Exercise:
Write a C++ program to add two distances in feet and inches form.
Click Here to View the Solution:
#include <iostream>
using namespace std;
struct dist
{
int feet;
float inch;
}
dis1 , dis2, add;
int main()
{
cout << "1st measure (feet-inches)" << endl;
cout << "Insert feet: ";
cin >> dis1.feet;
cout << "Insert inches: ";
cin >> dis1.inch;
cout << "\n2nd measure (feet-inches)" << endl;
cout << "Insert feet: ";
cin >> dis2.feet;
cout << "Insert inches: ";
cin >> dis2.inch;
add.feet = dis1.feet+dis2.feet;
add.inch = dis1.inch+dis2.inch;
if(add.inch > 12) //if inch is greater than 12 change it to feet
{
++ add.feet;
add.inch -= 12;
}
cout << endl << "total sum of the measures = " << add.feet << " feet " << add.inch << " inches";
return 0;
}
Click Here to View the Output:
1st measure (feet-inches) Insert feet: 5 Insert inches: 7 2nd measure (feet-inches) Insert feet: 6 Insert inches: 0 total sum of the measures = 11 feet 7 inches
Click Here to View the Explanation:
- A structure
dist
is created with two variablesfeet
andinch
.inch
variable isfloat
type so that it can accept decimals.feet
variable is an
type variable.int
- Three variables are initialized
dis1
,dis2
andadd
. - The user enters the first distance in feet and inches. The structure saves the distance in
dis1
. - The second distance is requested from the user and saved in the structure variable
dis2
. - The distances are added and stored in another structure variable,
add
. - In order to process the value of
inch
more than 12, anif... else
statement is used. This converts inches to feet and adds the value tofeet
. - The output is displayed on the screen.