Write a program that will read in a length in feet and inches and output the equivalent length in meters and centimeters. Use at least three functions: one for input, one or more for calculating, and one for output. Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program. There are 0.3048 meters in a foot, 100 centimeters in a meter, and 12 inches in a foot.
C++ program code:
//header section
#include <iostream>
using namespace std;
// 1 Function to read the length in feet and inches from the user
void readLength(int& feet, int& inches)
{
cout << "Enter the length in feet: ";
cin >> feet;
cout << "Enter the length in inches: ";
cin >> inches;
}
//2 Function to convert length from feet and inches to meters and centimeters
void convertToMetersAndCentimeters(int feet, int inches, double& meters, int& centimeters)
{
double totalInches = feet * 12 + inches;
meters = totalInches * 0.0254; // 1 inch is equal to 0.0254 meters
centimeters = static_cast<int>((meters - static_cast<int>(meters)) * 100);
}
//3 Function to output the equivalent length in meters and centimeters
void outputLength(int feet, int inches, double meters, int centimeters)
{
cout << feet << " feet and " << inches << " inches is equivalent to ";
cout << meters << " meters and " << centimeters << " centimeters." << endl;
}
//main method
int main()
{
//declare variable
char repeat;
//uses a do-while loop to allow the user to repeat the computation
//for new input values until they choose to end the program
//by entering 'n' or 'N' when prompted.
do
{
int feet, inches;
double meters;
int centimeters;
// Read length in feet and inches from the user
readLength(feet, inches);
// Convert length to meters and centimeters
convertToMetersAndCentimeters(feet, inches, meters, centimeters);
// Output the equivalent length in meters and centimeters
outputLength(feet, inches, meters, centimeters);
// Ask if the user wants to repeat the computation
cout << "Do you want to enter another length? (y/n): ";
cin >> repeat;
} while (repeat == 'y' || repeat == 'Y');
return 0;
}
Output of the program code:
Enter the length in feet: 400
Enter the length in inches: 40
400 feet and 40 inches is equivalent to 122.936 meters and 93 centimeters.
Do you want to enter another length? (y/n): y
Enter the length in feet: 50
Enter the length in inches: 1000
50 feet and 1000 inches is equivalent to 40.64 meters and 64 centimeters.
Do you want to enter another length? (y/n): n