Hello, I am trying to create a function that accepts an integer and a double and squares both values. I have to pass the values by reference. I am new to c++ and don't understand this and I do not understand functions very much when trying to pass more than 1 value. When the function returns I have to write out both values. I don't understand the return statement much either. Maybe if someone can set me on the right track I would appreciate it. Thank you! Sorry for the sloppy code!

// prototype
int Sqr(int &x, double &y);


int main()
{
  int a;
  double b;
  cout << "Enter a number" << endl;
  cin >> a;

cout << Sqr(a, b) << endl;
  cout << "Enter a double" << endl;
  cin >> b;
cout << Sqr(a, b) << endl;
  return 0;
}

// function
int Sqr(int &x, double &y)
{
	
	x = x * x;
    y = y * y;
 return 0;


}

Why are you calling the function on line 12 before you have values for both a and b (you just end up with whatever garbage is in b to start with)? If you cout the return of the function all you will get is your zero you return at the end of the function.

Your function sends in a reference to each of the parameters. This means the function not working with copies of these variables, but the variables themselves. When you pass in a and b into the function (which become x and y just by virtue of your naming) from main they are squared and written back to themselves. The changes persist after the function has returned. So eliminate line 12 and 15 and cout a and b on line 15 instead.

You can overload the function so it chooses the right one:

int sqr(int& n)
{
	return n * n;
}

double sqr(double& d)
{
	return d * d;
}

If you call sqr like this:

double d = 3;

sqr(d);

It will run the function with return type double.

You can see it returns a variable of the type double by the name in front of the function.

int n = 4; 
int n2  = sqr(n) // Here sqr returns an integer to n2.
cout << n2; // n2 is now 16;

@Andreas5 :
the OP didn't want to have two functions. Though overloading could have been a possible (and perhaps more elegant) way of doing it but we possibly cannot go beyond specs...:)

@c++learner :
I hope you understood what jonsca suggested. As far as return statements are concerned do a quick study about them (and functions in general) from any standard C++ book. As far as this problem is concerned you probably don't require a return (as jonsca indirectly mentioned) because you are passing the variables by reference and that means that their new values will be overwritten on their previous values. So if a = 2 and b = 3.0, after your function call a = 4 and b = 9.0. And coming back to your main you can simply print these values. So change the prototype of the function as

void Sqr (int &x, double &y);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.