Pass by reference issue C++

Drakorex

Could someone help explain why when I multiply 2 numbers it returns 0, but 3 and 4 numbers it works?

I wrote this for a class but I just cant see whats wrong with it, Thanks.

Function is to multiply 2,3, or 4 numbers using overloaded functions and passing the product by reference.

#include <iostream>
using namespace std;

void mult(int& product, int n1, int n2);
void mult(int& product, int n1, int n2, int n3);
void mult(int& product, int n1, int n2, int n3, int n4);

int main() {
    int product, n1, n2, n3, n4;
    char ans;

    do {
        product = 0;
        n1 = 0;
        n2 = 0;
        n3 = 0;
        n4 = 0;
        cout << "Enter 2-4 numbers to multiply\n";
        cout << "First number: ";
        cin >> n1;
        cout << "Second number: ";
        cin >> n2;
        cout << "Enter a 3rd number? (y/n):";
        cin >> ans;

        if (ans == 'y') {
            cout << "Third number: ";
            cin >> n3;
            cout << "Enter a 4th number? (y/n):";
            cin >> ans;
        } else {
            mult(product, n1, n2);
        }

        if (ans == 'y') {
            cout << "Fourth number: ";
            cin >> n4;
            mult(product, n1, n2, n3, n4);
        } else {
            mult(product, n1, n2, n3);
        }

        cout << "The product is " << product << endl << n1 << n2 << n3 << n4;
        cout << "Would you like to calculate another? (y/n):";
        cin >> ans;

    } while (ans == 'y');
}

Definitions

void mult(int& product, int n1, int n2)
{
    product = (n1 * n2);
    cout << product;
}
void mult(int& product, int n1, int n2, int n3)
{
    product = (n1 * n2 * n3);
}
void mult(int& product, int n1, int n2, int n3, int n4)
{
    product = (n1 * n2 * n3 * n4);
}
Captain Giraffe

It is because your control structures executes the statement

else{mult(product,n1,n2,n3);}

Even when you only intended mult(product,n1,n2). With only two numbers, n3 will be 0. So the result is zero as well.

You can solve it by restructuring it like this:

   cout << "Enter a 3rd number? (y/n):";
    cin >> ans;

    if (ans == 'y') {
        cout << "Third number: ";
        cin >> n3;
        cout << "Enter a 4th number? (y/n):";
        cin >> ans;
        if (ans == 'y') {
            cout << "Fourth number: ";
            cin >> n4;
            mult(product, n1, n2, n3, n4);
        } else {
            // Three numbers
            mult(product, n1, n2, n3);
        }
    } else {
        // Two numbers
        mult(product, n1, n2);
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related