有人可以幫助解釋爲什麼當我乘以2的數字它返回0,但3和4號碼的作品?通過引用問題C++
我寫了一個類,但我只是不能看到它有什麼問題,謝謝。
功能是使用重載函數乘以2,3或4個數字,並通過引用傳遞產品。
#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');
}
定義
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);
}
不同的方法來解決此問題:一個函數具有默認參數,傳遞一個數字向量,等等。另外,您可能希望在您的'mult'函數中執行或不執行'cout << product'時保持一致。 – crashmstr
感謝您的幫助,cout <<功能中的產品來自調試,我忘了將其刪除。 – Drakorex