gpt4 book ai didi

c++ - 通过引用问题 C++

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:44 25 4
gpt4 key购买 nike

有人可以帮助解释为什么当我将 2 个数字相乘时它返回 0,但 3 和 4 个数字却有效吗?

我是为一个类(class)写的,但我看不出它有什么问题,谢谢。

功能是使用重载函数将 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);
}

最佳答案

因为你的控制结构执行了语句

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

即使您只想要 mult(product,n1,n2)。只有两个数字,n3 将为 0。因此结果也为零。

你可以像这样重组它来解决它:

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

关于c++ - 通过引用问题 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com