Hello, I can't seem to figure out why my program isnt working. It keeps returning 0 kilograms and 0 grams. I know my function is being called properly because I checked with a cout statement, and I know the math itself works because I ran in directly in the main program, but for some reason once its in the function it does not work.
#include <iostream>
#include <cmath>
using namespace std;
double conversion (double pounds, double ounces);
int main()
{
double pounds, ounces, grams, kilograms;
pounds = 100;
ounces = 100;
while (pounds != 0 && ounces != 0)
{
cout << "Please enter the number of pounds the item wieghs and press enter, then enter the number of ounces left over and press enter. If you do not wish to continue enter a wieght of 0 pounds and 0 ounces.\n";
cin >> pounds;
cin >> ounces;
conversion (pounds, ounces);
cout << "The item wieghs " << kilograms << " kilograms and " << grams << " grams.\n";
}
return 0;
}
Within your conversion() function, you're storing the results in local variables called kilograms and grams. These are not the same variables as the ones you've declared in main(), despite having the same name.
You need to pass the calculated values back from conversion() to main(). My recommendation would be to add them to the function arguments, as references.
If that is what you want to do, you must use a global variable.
No. Using global variables is a very bad habit to get into. It's utterly untrue to say that you "must" use them. There are many ways to pass the results of a calculation in a function back to the calling code, and most of them are much better than using global variables.