C++ Conversion Not Working


#include <iostream>
using namespace std;
/*Use void functions, they perform some action but do not return a value*/

//Function Protoype, input,read in feet and inches:
void input (double&  feet, double& inches);
//Function Prototype, calculate, calculate with given formulae.
void calculate(double& feet, double& inches);
//Function Prototype, output, outputs calculations to screen.
void output (double meters, double centimeters);  

int main () 
    double feet;
    double inches;
    char repeat;

        //Call input:
        input(feet, inches);
        //Call calculate:
        calculate(feet, inches);
        //Call output:
        output (feet, inches);
        cout << "\n";
        cout << "Repeat? (Y/N): ";
        cin >> repeat;
        cout << "\n";
    while (repeat == 'Y' || repeat == 'y');

//Input function definition:
void input (double&  feet, double& inches)
    cout << "Please enter the length in feet" << endl;
    cin >> feet;

    cout << "Please enter the length in inches" << endl;
    cin >> inches;

//Calculate function definition, insert formulae here:
void calculate (double& feet, double& inches)

    feet = (feet * 0.3048);
     inches = (inches * 2.54);

//Output function definition:
void output (double meters, double centimeters)
    cout << meters << " meters & " << centimeters << " cm's. " << endl;

Why is my conversion not working?
Or what am I doing wrong?

Objective: Given a length in feet and inches I am suppose to output an equivalent length in meters and centimeters.

//Calculate function definition, insert formula here:
void calculate (double& feet, double& inches)
     feet = (feet * 0.3048);
  inches = (inches * 2.54);

Best Solution

That seems a bizarre way of doing it, changing the actual input variables. I would opt instead for:

void calculate (double feet, double inches, double& meters, double& centimeters) {
    double all_inches = feet * 12.0 + inches;
    centimeters = all_inches * 2.54;
    meters = int (centimeters / 100.0);
    centimeters -= (meters * 100.0);

In any case, even if you do use the same variables for input and output (and then they should be renamed to something more appropriate), it's still easiest to convert to a single form (inches) then do the conversion to centimeters then back to m/cm.

In your current code, if you pass in 1ft,0in, you'll get back 0.3048m,0cm rather than the more correct 30.48cm. By using the code in this answer, it will be converted first to 12.0 inches, then from there to 30.48cm, then to 0m,30.48cm.

Similarly, four and a half feet (4ft,6in) will first be converted to 54 inches, then to 137.16cm, then to 1m,37.16cm.

Related Question