feet
and inch
. #include <iostream>
using namespace std;
struct Distance {
int feet;
float inch;
}d1 , d2, sum;
int main() {
cout << "Enter 1st distance," << endl;
cout << "Enter feet: ";
cin >> d1.feet;
cout << "Enter inch: ";
cin >> d1.inch;
cout << "\nEnter information for 2nd distance" << endl;
cout << "Enter feet: ";
cin >> d2.feet;
cout << "Enter inch: ";
cin >> d2.inch;
sum.feet = d1.feet+d2.feet;
sum.inch = d1.inch+d2.inch;
// changing to feet if inch is greater than 12
if(sum.inch > 12) {
// extra feet
int extra = sum.inch / 12;
sum.feet += extra;
sum.inch -= (extra * 12);
}
cout << endl << "Sum of distances = " << sum.feet << " feet " << sum.inch << " inches";
return 0;
}
Enter 1st distance,
Enter feet: 12
Enter inch: 6
Enter information for 2nd distance
Enter feet: 6
Enter inch: 2
Sum of distances = 18 feet 8 inches
Distance
containing two data members (inch
and feet
) is declared to store the distance in the inch-feet system.d1
and d2
are created to store the distance entered by the user. And, the sum variable stores the sum
of the distances.if
statement is used to convert inches to feet if the value of inch
of sum
variable is greater than 12
:int
variable extra
stores the extra
feet gained due to the value of inch being greater than 12
. This is obtained from the quotient of division between sum.inch
and 12
.sum.feet
.sum.inch
is then calculated by subtracting extra * 12
from its initial value.#include <iostream>
using namespace std;
struct Distance
{
int feet;
int inch;
};
void displayDistance(Distance d);
Distance addDistance(Distance d1, Distance d2);
int main()
{
Distance d1 = {10, 6};
Distance d2 = {5, 10};
Distance sum = addDistance(d1, d2);
cout << "First distance: ";
displayDistance(d1);
cout << "Second distance: ";
displayDistance(d2);
cout << "Sum of distances: ";
displayDistance(sum);
return 0;
}
void displayDistance(Distance d)
{
cout << d.feet << " feet " << d.inch << " inches" << endl;
}
Distance addDistance(Distance d1, Distance d2)
{
Distance sum;
sum.feet = d1.feet + d2.feet;
sum.inch = d1.inch + d2.inch;
if (sum.inch >= 12)
{
sum.feet++;
sum.inch -= 12;
}
return sum;
}
First distance: 10 feet 6 inches
Second distance: 5 feet 10 inches
Sum of distances: 16 feet 4 inches
Distance
with two members feet
and inch
. The function displayDistance()
is used to display a distance in the inch-feet system. The function addDistance()
takes two distances as arguments and returns their sum.main()
function, we create two distances d1
and d2
and initialize them with values. We then call the addDistance()
function to add these distances and store the result in the sum
variable. Finally, we call the displayDistance()
function to display all three distances.