下面是我们被问到的问题和我们得到的代码。在我的同龄人中交谈,我们似乎找不到原因,任何见解都会很棒。
为什么答案是"最小值为6,最大值为5"?
#include <iostream>
using namespace std;
void minMax(double a, double b, double &min, double &max)
{
if (a<b)
{
double min = a;
double max = b;
}
else
{
double min = b;
double max = a;
}
}
int main()
{
double a = 5, b = 6, min = 6, max = 5;
minMax(a, b, min, max);
cout << " min is " << min << " and max is " << max;
system("PAUSE");
return 0;
}
您正在用局部变量定义来隐藏参数,以修复在课程日志上只写100次的问题(当然也要告诉您的同行):
void minMax(double a, double b, double &min, double &max)
{
if (a<b)
{
/* double here defines a variable in local scope
that shadows the reference parameter. */
min = a;
max = b;
}
else
{
min = b;
max = a;
}
}