Hi , I wrote a code (with this website's help) for conversion pounds to kilograms and kilograms to pounds. The problem is that it converts pounds to kilograms but not kilograms to pounds
You should do some research on the formulas to convert pounds to kilograms and kilograms to pounds. Both your formulas in "weightCalculating" are wrong. In "weightOutput" it prints the correct variables, but they have the wrong answers.
I would have set up the program different allowing the user to choose which way to convert and do each conversion separate,
#include <iostream>
usingnamespace std;
void kiloToPounds(double& kiloToPounds)
{
cout << kiloToPounds << " Kg in pounds is: ";
kiloToPounds=kiloToPounds/0.45359;
// http://www.rapidtables.com/convert/weight/how-kg-to-pound.htm
cout << kiloToPounds << " pounds" << endl;
}
void poundsToKilo(double& poundsToKilo)
{
cout << poundsToKilo << " pounds in kg is: ";
poundsToKilo = poundsToKilo * 0.45359; // http://www.rapidtables.com/convert/weight/how-pound-to-kg.htm
cout << poundsToKilo << "kg" << endl;
}
void weightInput()
{
cout << "Enter 1 for Kilo to pound conversion. Enter 2 for pound to Kilo conversion: ";
int choice;
cin >> choice;
cout << "\n\nEnter the weight: ";
double weight;
cin >> weight;
if (choice == 1)
{
kiloToPounds(weight);
}
elseif (choice == 2)
{
poundsToKilo(weight);
}
}
int main()
{
double kiloToPounds;
double poundsToKilo;
char userInput;
do
{
weightInput();
cout<< "Would you like to do another conversion?\n Y for yes or any other key to quit.";
cin>> userInput;
} while (userInput == 'Y' ||userInput == 'y'); // this picks up either y or Y.
return (0);
}
Thank you Andy. Thanks a lot TarikNeaj. TarikNeaj, your code works perfect and looks so nice. When I try to write code , there is always something wrong and it looks ugly. How do I improve ?
It's something you just learn overtime. When I was were you are, my code was also a mess. Keep writing, keep learning. You will get there, good job so far :)
you pass "kilograms" and "pounds" by reference which allows the variables in main to be changes. The problem is that line 3 will change the value of "kilograms" both in the function and in main. then when you use "kilograms" in line 4 it has the wrong value. A good point to make two separate functions that would return a value so as not to change your original input.
its not only the pass by ref, its that pounds uses kilos which was just modified.
he could still pass by ref to populate both values, but needs a temp...
t = p * 0.4;
p = k* 2.2;
k = t;
Personally, I would prefer 2 constants and be done with it.