Help with a loop.

I have finished my program to convert feet and inches to centimeters, but i need to insert a loop that will ask the user if they want to run the program again. Where can I insert it? Also can someone explain the last line of my second function, all i know is that it works, but i dont know why. Thank you.


#include <iostream>

using namespace std;

void get_feet_inch(int& feet, int& inches);
void convert_to_meters(int feet, int inches, int& meters, int& centimeters);
void show_results(int feet, int inches, int meters, int& centimeters);


int main()
{
int feet;
int inches;
int meters;
int centimeters;

get_feet_inch( feet, inches);
convert_to_meters(feet, inches, meters, centimeters);
show_results( feet, inches, meters, centimeters);

return 0;

}

void get_feet_inch(int& feet, int& inches)
{
cout << "Please input number of feet here ";
cin >> feet;
cout << "\n Please input number of inches here ";
cin >> inches;

}

void convert_to_meters(int feet, int inches, int& meters, int& centimeters)
{
const double meter_per_foot = 0.3048;
const double centimeter_per_meter = 100.00;
const double inches_per_foot = 12.00;
double feet_double = feet + inches / inches_per_foot;
double meters_double = feet_double * meter_per_foot;

meters = meters_double;
centimeters = (meters_double - meters) * centimeter_per_meter;
}

void show_results(int feet, int inches, int meters, int& centimeters)
{

cout << feet << " feet and "
<< inches << " inches "
<< " convert to " << meters << " meters "
<< "and " << centimeters << " Centimeters \n";
}
You could put a while loop in the main function asking the user if he or she wants to do it again. That would look something like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main() 
{
int feet;
int inches;
int meters;
int centimeters;
char letter;
do
{
get_feet_inch( feet, inches);
convert_to_meters(feet, inches, meters, centimeters);
show_results( feet, inches, meters, centimeters);
cout << "Would You like to perform task again: ";
cin >> letter;
}
while ( letter == 'y' || letter == 'Y');

return 0;

}

Adding a do while loop will make sure that it runs once and then it will ask the user if they want to do it again. If so, they enter y or Y and it will re run as long as the letter continues to be y or Y.
Also, which function do you not understand? What is the name of it?
1
2
meters = meters_double;
centimeters = (meters_double - meters) * centimeter_per_meter;


meters is an int variable, so the first line will assign the value stored in meters_double, rounded down to the nearest integer (ie truncate the decimals). So meters_double >= meters.

Does that help you understand?
Thank you for the loop it helped alot.
Yes i understand the function now thank you.
Topic archived. No new replies allowed.