所以我正在学习 C++,我必须创建一个重载函数,然后从一组数字中获取最大的数字。这适用于 2 个数字,但是当我注释掉对 2 个数字的函数调用并尝试使用 3 个数字的那个时,它给了我很多错误。我需要一双新的眼睛来看看我的代码,看看我做错了什么。
#include <iostream>
using namespace std;
// function prototypes
double max(double numberOne, double numberTwo);
double max(double numberOne, double numberTwo, double numberThree);
int main()
{
int numberOne,
numberTwo,
numberThree;
// user input
cout << "Input number 1: " << endl;
cin >> numberOne;
cout << "Input number 2: " << endl;
cin >> numberTwo;
cout << "Input number 3: " << endl;
cin >> numberThree;
cout << "The largest of " << numberOne << " and " << numberTwo << ": " << max(numberOne, numberTwo) << endl;
cout << "The largest of " << numberOne << ", " << numberTwo << ", and " << numberThree << ": " << max(numberOne, numberTwo, numberThree) << endl;
return 0;
}
// function declarations
double max(double numberOne, double numberTwo) {
// if number one is greater than number two return that
// otherwise return numberTwo as the greater value
if (numberOne > numberTwo) {
return numberOne;
} else {
return numberTwo;
}
}
double max(double numberOne, double numberTwo, double numberThree) {
// compare 1 and 2 to see which is greater
if (numberOne > numberTwo) {
if (numberOne > numberThree) {
// 2 is greater return it
return numberOne;
} else {
// else 3 is greater return that
return numberThree;
}
} else {
if (numberTwo > numberThree) {
// 2 is greater return it
return numberTwo;
} else {
// else 3 is greater return that
return numberThree;
}
}
}