C++ 问题是如何确定函数中最小数字的结果,以及如何返回它?
您需要决定是修改函数的参数还是返回单个值 修改参数 通过引用传递返回变量:C++ 问题是如何确定函数中最小数字的结果,以及如何返回它?,c++,function,C++,Function,您需要决定是修改函数的参数还是返回单个值 修改参数 通过引用传递返回变量: #include <iostream> using namespace std; int myNum1 = 0; int myNum2 = 0; int main() { int smaller, bigger, a, b; cout << " Enter two numbers :" << endl; cin >> a, b;
#include <iostream>
using namespace std;
int myNum1 = 0;
int myNum2 = 0;
int main() {
int smaller, bigger, a, b;
cout << " Enter two numbers :" << endl;
cin >> a, b;
smallerNumber(smaller, bigger, a, b);
cout << smaller << bigger << endl;
return 0;
}
int smallerNumber(int a, int b, int IsSmaller, int IsBigger){
if (a > b) {
a = IsBigger;
b = IsSmaller;
}
else if (a < b) {
a = IsSmaller;
b = IsBigger;
}
else if (a == b) {
a = IsSmaller;
b = IsBigger;
}
return a;
return b;
}
通过引用Pasing允许您的函数修改参数
返回多个值
要返回多个值,需要一个数据结构。
下面是一个使用struct的示例
void smallerNumber(int& a, int& b, int IsSmaller, int IsBigger)
{
if (a > b) {
a = IsBigger;
b = IsSmaller;
}
else if (a < b) {
a = IsSmaller;
b = IsBigger;
}
else if (a == b) {
a = IsSmaller;
b = IsBigger;
}
}
您当前的代码有什么问题?请详细描述一下。你给了它什么投入,它做了什么,你期望它做什么,到目前为止,你试图补救什么情况?你在编写代码的背后有什么想法?例如,为什么你把两个返回语句一个接一个地放进去,这背后的想法是什么;返回b;毫无意义。返回a后;函数结束,不再执行其他语句。如果要在main.cin>>a,b中使用smallerNumber,还需要在main之前声明smallerNumber;应该是cin>>a>>b;非常感谢,我想做的是修改参数,因为最大值或较小值的比较必须在函数中完成。我只是不知道如何通过引用返回它们。
struct BigSmall
{
int bigger;
int smaller;
};
BigSmall smallerNumber(int a, int b)
{
BigSmall result;
if (a > b) {
result.bigger = a;
result.smaller = b;
}
else if (a < b) {
result.bigger = b;
result.smaller = a;
}
else if (a == b) {
result.bigger = a;
result.smaller = a;
}
return result;
}