program not returning proper values

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;
}

double conversion (double pounds, double ounces)
{
double mass1, mass2, kilograms, grams, counter;
mass1 = pounds + (ounces/16);
mass2 = mass1 * 0.453592;
for (double kilograms = 0; mass2 > 1; mass2--)
{
counter++;
}
mass2 = mass2 * 1000;
grams = mass2;
kilograms = counter;
}

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.
how do i do that?
Look in the tutorials on this site for information about references.
Recommend you read about code tags.
http://www.cplusplus.com/articles/z13hAqkS/

You define kilograms and grams in main and in conversion.

If that is what you want to do, you must use a global variable.
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.
1
2
double conversion (double pounds, double ounces)
{

EDIT
try this instead...
1
2
void conversion (double& pounds, double& ounces)
{


this allows you to pass by reference.
Last edited on
closed account (EwCjE3v7)
Maybe if u put your code in [.code] actual code [/code.] without the dots it will be easier to read
Also, using doubles in a for loop is bad news, use ints and convert them to doubles in the body of the loop.

What is the purpose of that for loop anyway? It is just a one off conversion - so why the loop with a counter variable?

HTH
Topic archived. No new replies allowed.