Writing 3 functions to convert feet and inches to meters and centimeters in C++?

Kareem Youssef picture Kareem Youssef · May 9, 2014 · Viewed 15.5k times · Source

i'm trying to write a C++ program that consists of 3 functions one for input , one for the calculation and one for output . The program is supposed to take feet and inches as input then print the converted value of meters and centimeters back to the user . I think there's something wrong with calling by reference since i'm still learning how to use it properly , anyways here's the code

#include<iostream>
using namespace std;
void input(double feet , double inches);
void calc(double &feet , double &inches);
void output(double &feet , double &inches);
void main()
{
 double feet1 , inches1;
 char ans;
 do
 {
  input(feet1,inches1);
  calc(feet1,inches1);
  output(feet1,inches1);
  cout<<"Would you like to calculate again? y/n : ";
  cin>>ans;
 }
 while(ans == 'y' || ans == 'Y');
}
void input(double feet , double inches)
{
 cout<<"Enter feet : ";
 cin>>feet;
 cout<<"Enter inches : ";
 cin>>inches;
}
void calc(double &feet , double &inches)
{
 double meters , centimeters;
 meters = feet * 0.3048;
 centimeters = inches * 2.54;
}
void output(double &feet , double &inches)
{
 calc(feet,inches);
 cout<<"Converted feet to metres : "<<metres;
 cout<<"Converted inches to centimeters : "<<centimeters;
}

Answer

Some programmer dude picture Some programmer dude · May 9, 2014

You have (at least) three problems: The first is that you modify the arguments passed to the input function, but as arguments are passed by value (i.e. copied) you are only modifying the copies. You need to pass the arguments by reference (which you do with the other functions, even when you don't need it for them).

The second problem is that in your calc function you declare meters and centimeters as local variables. Once the function returns those variables goes out of scope and can't be referenced from anywhere else.

The third problem, and this should give you a compilation error, is that you try to use metres (check spelling, it's not the same as in calc) and centimeters from the output function, and there those variables are not declared.