1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#include <iostream>
using namespace std;
//Function Prototype
void MulAdd(int x, int y, int &product, int &sum);
int *MulAdd(int x, int y);
/*
* Chapter 13 Problem 4
*
* Write a function that takes two arguments and provides two
* separate results to the caller, one that is the result
* of multiplying the two arguments, the other the result of
* adding them. Since you can directly return only one value
* from a function, you'll need the second value to be returned
* through a pointer or reference parameter.
*
* Use a pointer inside the function to return the results of
* the addition.
*/
int main()
{
// Declare and initialize variables
int x = 0;
int y = 0;
// Ask user for x and y values
cout << "Please enter a value for x: ";
cin >> x;
cout << "Please enter a value for y: ";
cin >> y;
//Option 1: No return: Reference, new variables;
int product, sum;
MulAdd(x,y,product,sum);
cout << "x * y = " << product << "; x + y = " << sum << endl;
//Option 2: Return by pointer to array[2];
int *m_result = MulAdd(x, y);
cout << "x * y = " << m_result[0] << "; x + y = " << m_result[1] << endl;
}
//Possible referenced parameter: 4 arguments:
void MulAdd(int x, int y, int &product, int &sum)
{
product = x*y;
sum = x+y;
}
//Possible pointer return:
int* MulAdd(int x, int y)
{
static int arry[2];
arry[0] = x*y;
arry[1] = x+y;
int *results = arry;
return results;
}
|
Please enter a value for x: 5
Please enter a value for y: 10
x * y = 50; x + y = 15
x * y = 50; x + y = 15 |